一、多对一
一个Product对应一个Category,一个Category对应多个Product,所以Product和Category是多对一的关系。使用hibernate实现多对一。
1.准备Category类
1 package hibernate.pojo; 2 3 import java.util.Set; 4 5 public class Category { 6 int id; 7 String name; 8 9 public int getId() { 10 return id; 11 } 12 13 public void setId(int id) { 14 this.id = id; 15 } 16 17 public String getName() { 18 return name; 19 } 20 21 public void setName(String name) { 22 this.name = name; 23 } 24 25 }
2.准备Category.hbm.xml
1 <?xml version="1.0"?> 2 3 <!DOCTYPE hibernate-mapping PUBLIC 4 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 5 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 6 <hibernate-mapping package="hibernate.pojo"> 7 <class name="Category" table="category"> 8 <!-- <cache usage="read-only"/> --> 9 <id name="id" column="id"> 10 <generator class="native"> 11 </generator> 12 </id> 13 <property name="name" /> 14 </class> 15 </hibernate-mapping>
3.为Product.java增加Category属性
1 Category category; 2 public Category getCategory() { 3 return category; 4 } 5 6 public void setCategory(Category category) { 7 this.category = category; 8 }
4.在Product.hbm.xml中设置Category多对一关系
1 <?xml version="1.0"?> 2 <!DOCTYPE hibernate-mapping PUBLIC 3 "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 4 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 5 6 <hibernate-mapping package="hibernate.pojo"> 7 <class name="Product" table="product"> 8 <id name="id" column="id"> 9 <generator class="native"> 10 </generator> 11 </id> 12 <property name="name" /> 13 <property name="price" /> 14 <many-to-one name="category" class="Category" column="cid"></many-to-one> 15 </class> 16 17 </hibernate-mapping>
使用many-to-one 标签设置多对一关系
name="category" 对应Product类中的category属性
class="Category" 表示对应Category类
column="cid" 表示指向 category_表的外键
5.在hibernate.cfg.xml中增加Category的映射
1 <mapping resource="hibernate/pojo/Category.hbm.xml" />
6.测试
二、一对多
三、多对多
原文:https://www.cnblogs.com/lyj-gyq/p/9188565.html