首页 > 代码库 > hibernate之关于一对多单向关联映射
hibernate之关于一对多单向关联映射
@Entity @Table(name="t_group") publicclass Group { private Integer id; private String name; private Set<Person> persons=newHashSet<Person>();//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 //加上@JoinColumn是为了防止Hibernate将一对多当做多对多来处理,产生中间表 @JoinColumn(name="group_id") public Set<Person>getPersons() { returnpersons; } publicvoidsetPersons(Set<Person> persons){ this.persons = persons; } }
@Entity @Table(name="t_person") publicclass Person { private Integer id; private String name; private Integer age; @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; } @Column(name="t_age") public Integer getAge() { returnage; } publicvoid setAge(Integerage) { this.age = age; } }
XML配置一对多的单向关联映射
publicclass Person { private Integer id; private String name; private Integer age; public Integer getId() { returnid; } publicvoid setId(Integerid) { this.id = id; } public String getName() { returnname; } publicvoid setName(Stringname) { this.name = name; } public Integer getAge() { returnage; } publicvoid setAge(Integerage) { this.age = age; } }
publicclass Group { private Integer id; private String name; private Set<Person> persons=newHashSet<Person>();//set不允许重复,最适合数据库模型 public Integer getId() { returnid; } publicvoid setId(Integerid) { this.id = id; } public String getName() { returnname; } publicvoid setName(Stringname) { this.name = name; } public Set<Person>getPersons() { returnpersons; } publicvoidsetPersons(Set<Person> persons) { this.persons = persons; } }
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="csg.hibernate.entity"> <class name="Group"table="t_group"> <id name="id"> <column name="id"/> <generator class="native" /> </id> <property name="name" /> <set name="persons"> <key column="group_id"/> <one-to-many class="csg.hibernate.entity.Person"/> </set> </class> </hibernate-mapping>
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="csg.hibernate.entity"> <class name="Person"table="t_person"> <id name="id"> <column name="id"/> <generator class="native" /> </id> <property name="name" /> <property name="age" /> </class> </hibernate-mapping>
hibernate之关于一对多单向关联映射
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。