hibernate4之一对多关系映射
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hibernate4之一对多关系映射相关的知识,希望对你有一定的参考价值。
示例:一个部门(Department )下面有多个用户(User),多个用户对应一个部门
public class Department { private Integer id; private String name; private Set<User> users; //getter and setter }
public class User{ private Integer id; private String userName; private Department department; //getter and setter }
用XML映射
<hibernate-mapping package="com.shen.hibernate4.entity"> <class name="Department " table="tb_department "> <id name="id"> <generator class="identity" /> </id> <property name="name" /> <!--反转:设置从User端加入数据失效,不维护关联关系。注:Hibernate默认inverse="false"为主控方,由主控方负责维护对象的关系联系。--> <set name="users" inverse="true"> <key column="department_id" /> <one-to-many class="User"/> </set> </class> </hibernate-mapping> <hibernate-mapping package="com.shen.hibernate4.entity"> <class name="User" table="tb_user"> <id name="id"> <generator class="identity"/> </id> <property name="userName" column="user_name"/> <!-- 此处需要与Department 端的配置的字段保持一致--> <many-to-one name="department" column="department_id" class="Department " not-null="true"/> </class> </hibernate-mapping>
用@Annotation映射
@Entity @Table(name = "tb_department") public class Category { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String name; //mappedBy 值为User中Department类型属性 @OneToMany(mappedBy = "department") private Set<User> users; //getter and setter }
@Entity @Table(name = "tb_user") public class User{ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private String userName; @ManyToOne @JoinColumn(name = "department_id", nullable = false) private Department department; //getter and setter }
本文出自 “冰葫芦” 博客,请务必保留此出处http://shenlang7.blog.51cto.com/3102414/1742804
以上是关于hibernate4之一对多关系映射的主要内容,如果未能解决你的问题,请参考以下文章
mybatis xml数据层框架应用--Mybatis关系映射之一对多关系映射