我有3张桌子:
实体
CREATE TABLE `entity` (
`entity_number` bigint(20) NOT NULL AUTO_INCREMENT,
`title` varchar(6) DEFAULT NULL,
`name` varchar(45) NOT NULL,
`surname` varchar(45) NOT NULL,
`id_number` varchar(13) DEFAULT NULL,
`gender` varchar(7) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`date_of_birth` datetime DEFAULT NULL,
`preferred_language` varchar(10) DEFAULT NULL,
`ethnic_group` varchar(15) DEFAULT NULL,
`username` varchar(20) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL,
`status` varchar(10) DEFAULT NULL,
PRIMARY KEY (`entity_number`),
UNIQUE KEY `id_number_UNIQUE` (`id_number`)
)
联系人
CREATE TABLE `contacts` (
`contact_id` int(11) NOT NULL AUTO_INCREMENT,
`contact_type` varchar(25) NOT NULL,
`value` varchar(100) NOT NULL,
PRIMARY KEY (`contact_id`),
UNIQUE KEY `contact_id_UNIQUE` (`contact_id`)
)
con_contact_entity
CREATE TABLE `con_contact_entity` (
`entity_number` bigint(20) NOT NULL,
`contact_id` int(11) NOT NULL,
PRIMARY KEY (`entity_number`,`contact_id`),
KEY `FK_ENTITY_NUMBER` (`entity_number`),
KEY `FK_CONTACT_ID` (`contact_id`),
CONSTRAINT `FK_CONTACT_ID` FOREIGN KEY (`contact_id`) REFERENCES `contacts` (`contact_id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `FK_ENTITY_NUMBER` FOREIGN KEY (`entity_number`) REFERENCES `entity` (`entity_number`) ON DELETE NO ACTION ON UPDATE NO ACTION
)
然后我有我的3个pojos :(只粘贴相关部分)
实体
@javax.persistence.Entity
@Table (name = "ENTITY")
@Inheritance (strategy = InheritanceType.JOINED)
public class Entity {
@ManyToMany (targetEntity = Contact.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
@JoinTable (name = "con_contact_entity", joinColumns = @JoinColumn (name = "entity_number"), inverseJoinColumns = @JoinColumn (name = "contact_id"))
private Set<Contact> contactInfo;
...
}
与
@XmlAccessorType (XmlAccessType.NONE)
@XmlType (name = "Contact", propOrder = {"typeOfContact", "contactValue"})
@Entity @Table (name = "CONTACTS")
public class Contact {
@Id
@GeneratedValue
private Long contact_id;
@XmlElement (name = "TypeOfContact", required = true, nillable = false)
@Column (name = "contact_type") @Enumerated (EnumType.STRING)
private ContactType typeOfContact;
@XmlElement (name = "ContactValue", required = true, nillable = false)
@Column (name = "value")
private String contactValue;
...
}
如果我将JOE添加为具有联系人详细信息的实体(Type = HomeTel,Value = 123456789),然后添加想要添加相同联系人详细信息的JOE的妻子,则Contact表中会有重复的条目。如何对现有副本进行hibernate检查,如果找到,只需在con_contact_entity表中引用这些联系人详细信息。
示例:结果表数据为:
**ENTITY**
123 MR JOE ....
124 MRS JANE ....
**CON_CONTACT_ENTITY**
123 1
124 1
**CONTACTS**
1 HOMETEL 123456789