案例:電商業務中,一個用戶對應多個收貨地址,即一個user對多個address:java
1.在User.java屬性中新增屬性數據庫
private Set<Address> addresses = new HashSet<Address>();
或:session
private List<Address> addersslist = new ArrayList<Address>();
2.新增address.javaapp
package com.qfedu.entity; public class Address { private Long id; private String name; //...getters and setters, constructs ,tostring() }
注意:當在User中使用List<Address>時,必須定義一個字段,用於表示順序 private int add_index;測試
3.新增 address.hbm.xmlui
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- name:類名 table:表名 --> <class name="com.qfedu.entity.Address" table="address"> <!-- 主鍵 --> <id name="id" column="id"> <generator class="native"></generator> </id> <!-- 其餘屬性 --> <property name="name" column="name"></property> </class> </hibernate-mapping>
並在hibernate.cfg.xml中加入配置:spa
<mapping resource="com/qfedu/entity/address.hbm.xml"/>
4.修改user.hbm.xml,新增:hibernate
<set name="addresses"> <key column="user_id"></key> <one-to-many class="com.qfedu.entity.Address"></one-to-many> </set>
或xml
<list name="addersslist"> <key column="user_id"></key> <!-- index標籤表示多的一方對應一的一方的索引位置 column屬性表示數據庫中存放數據的字段 index爲關鍵字 避免跟關鍵字衝突 --> <index column="add_index" type="java.lang.Integer"></index> <one-to-many class="com.qfedu.entity.Address"></one-to-many> </list>
5.測試對象
public static void main( String[] args ) { //1.建立sessionFactory對象 SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); //2.建立session對象 Session session= sessionFactory.openSession(); //3.開啓事務 Transaction tx = session.beginTransaction(); //4.執行 User u = new User(); u.setName("zhangsan"); u.setAge(18); Address ad1= new Address(); ad1.setName("beijing"); Address ad2= new Address(); ad2.setName("qingdao"); u.getAddresses().add(ad1); u.getAddresses().add(ad2); session.save(ad1); session.save(ad2); session.save(u); //5.提交事務 tx.commit(); //6.關閉session session.close(); sessionFactory.close(); }
6.觀察數據庫中的數據。