1.一对多one-to-many
案例:电商业务中,一个用户对应多个收货地址,即一个user对多个address:
1.在User.java属性中新增属性
private Set<Address> addresses = new HashSet<Address>();
或:
private List<Address> addersslist = new ArrayList<Address>();
2.新增address.java
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.xml
<!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中加入配置:
<mapping resource="com/qfedu/entity/address.hbm.xml"/>
4.修改user.hbm.xml,新增:
<set name="addresses"> <key column="user_id"></key> <one-to-many class="com.qfedu.entity.Address"></one-to-many> </set>
或
<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.观察数据库中的数据。