1.一对多one-to-many
案例:电商业务中,一个用户对应多个收货地址,即一个user对多个address:
1.在User.java属性中新增属性
private Set addresses = new HashSet();
或:
private List addersslist = new ArrayList();
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
并在hibernate.cfg.xml中加入配置:
4.修改user.hbm.xml,新增:
或
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.观察数据库中的数据。