示例:一个部门(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/1742805
原文地址:http://shenlang7.blog.51cto.com/3102414/1742805