筆記45 Hibernate快速入門(二)
阿新 • • 發佈:2018-06-15
pre 快速入門 -- ret hbm spa -m int property
Hibernate O/R 映射
一、多對一
一個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"?> 23 <!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.測試
二、一對多
三、多對多
筆記45 Hibernate快速入門(二)