【Hibernate】之关于一对多,多对一双向关联映射
由于一对多,和多对一的双向关联映射基本上一样,所以这里就一起写下来!
Annotations配置
@Entity@Table(name="t_group")publicclass Group { private Integer id; private String name; private Setpersons=newHashSet ();//set不允许重复,最适合数据库模型 @Id @GeneratedValue public Integer getId() { returnid; } publicvoid setId(Integerid) { this.id = id; } @Column(name="t_name") public String getName() { returnname; } publicvoid setName(Stringname) { this.name = name; } @OneToMany(mappedBy="group")//意识是告诉Hibernate的关联关系应该设在Person,多的一方// 只有OneToOne,OneToMany,ManyToMany上才有mappedBy属性,ManyToOne不存在该属性; public Set getPersons() { returnpersons; } publicvoidsetPersons(Set persons) { this.persons = persons; }}
@Entity@Table(name="t_person")publicclass Person { private Integer id; private String name; private Integer age; private Group group; @ManyToOne public Group getGroup() { returngroup; } publicvoid setGroup(Groupgroup) { this.group = group; } @Id @GeneratedValue public Integer getId() { returnid; } publicvoid setId(Integerid) { this.id = id; } @Column(name="p_name") public String getName() { returnname; } publicvoid setName(Stringname) { this.name = name; } @Column(name="p_age") public Integer getAge() { returnage; } publicvoid setAge(Integerage) { this.age = age; }}
XML配置
由上大家都可以得出疑问?
为什么双向关联在Group中key需要指定column而在Person中也需要指定column呢?
如果其中一个不指定会有什么后果?
如果指定的column不一致又会有什么后果?
大家可以试一下!