1、POJO的建立
/** * 客户表 */ public class TbUser { private Long id; private String name; private Long age; private String city; //订单 private Set<Order> orders = new HashSet<Order>(); public TbUser(){ } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getAge() { return age; } public void setAge(Long age) { this.age = age; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } @Override public String toString() { return "TbUser [id=" + id + ", name=" + name + ", age=" + age + ", city=" + city + "]"; } public Set<Order> getOrders() { return orders; } public void setOrders(Set<Order> orders) { this.orders = orders; } }
/** * 订单表 */ public class Order { private Long id; private String addr; private Long totalprice; //用户 private TbUser user; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public Long getTotalprice() { return totalprice; } public void setTotalprice(Long totalprice) { this.totalprice = totalprice; } public TbUser getUser() { return user; } public void setUser(TbUser user) { this.user = user; } @Override public String toString() { return "Order [id=" + id + ", addr=" + addr + ", totalprice=" + totalprice + ", user=" + user + "]"; } }
2、POJO.hbm.xml
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- 映射关系配置 name="POJO类" table="表单名称" catalog="数据库名称,若不指定则使用jdbc中的配置" --> <class name="com.study.hibernate.domain.TbUser" table="tb_user" catalog="db_hibernate" select-before-update="true"> <!-- 配置主键 name="POJO中对应属性" colum="表单中主键名" type="数据类型" --> <id name="id" column="id" type="java.lang.Long"> <!-- 主键的生成方式。native:根据底层数据库自动选择 --> <generator class="native"></generator> </id> <property name="name" column="name" type="java.lang.String"></property> <property name="age" column="age" type="java.lang.Long"></property> <property name="city" column="city" type="java.lang.String"></property> <!-- 此处的name是对应实体对象中的属性名 --> <!-- cascade级联操作 save-update为自动保存-修改 --> <set name="orders" cascade="save-update"> <!-- 此处的column是对应Order.hbm.xml中many-to-one的column="tb_user_id" --> <key column="tb_user_id"/> <one-to-many class="com.study.hibernate.domain.Order"/> </set> </class> </hibernate-mapping>
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <!-- 映射关系配置 name="POJO类" table="表单名称" catalog="数据库名称,若不指定则使用jdbc中的配置" --> <class name="com.study.hibernate.domain.Order" table="tb_order" catalog="db_hibernate"> <!-- 配置主键 name="POJO中对应属性" colum="表单中主键名" type="数据类型" --> <id name="id" column="id" type="java.lang.Long"> <!-- 主键的生成方式。native:根据底层数据库自动选择 --> <generator class="native"></generator> </id> <property name="addr" column="addr" type="java.lang.String"></property> <property name="totalprice" column="totalprice" type="java.lang.Long"></property> <many-to-one name="user" class="com.study.hibernate.domain.TbUser" column="tb_user_id" /> </class> </hibernate-mapping>
3、测试
1)级联保存
public void saveTest(){ Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); TbUser u = new TbUser(); u.setName("tl"); u.setAge(25L); u.setCity("beijing"); Order o1 = new Order(); o1.setAddr("ccccc"); o1.setTotalprice(100L); Order o2 = new Order(); o2.setAddr("ssssss"); o2.setTotalprice(200L); u.getOrders().add(o1); u.getOrders().add(o2); o1.setUser(u); o2.setUser(u); session.save(u); //当<set> cascade='save-update'时不用写下面保存代码也可保存 // session.save(o1); // (1) // session.save(o2); // (2) transaction.commit(); session.close(); sessionFactory.close(); //当没有配置cascade='save-update'并取消(1)(2)注释时 //结果1 // Hibernate: /* insert com.study.hibernate.domain.TbUser */ insert into db_hibernate.tb_user (name, age, city) values (?, ?, ?) // Hibernate: /* insert com.study.hibernate.domain.Order */ insert into db_hibernate.tb_order (addr, totalprice, tb_user_id) values (?, ?, ?) // Hibernate: /* insert com.study.hibernate.domain.Order */ insert into db_hibernate.tb_order (addr, totalprice, tb_user_id) values (?, ?, ?) // Hibernate: /* create one-to-many row com.study.hibernate.domain.TbUser.orders */ update db_hibernate.tb_order set tb_user_id=? where id=? // Hibernate: /* create one-to-many row com.study.hibernate.domain.TbUser.orders */ update db_hibernate.tb_order set tb_user_id=? where id=? //结果2:为没有执行session.save(o1); session.save(o2); Hibernate 自动执行保存O1,O2对象并与user关联 // Hibernate: /* insert com.study.hibernate.domain.TbUser */ insert into db_hibernate.tb_user (name, age, city) values (?, ?, ?) // Hibernate: /* insert com.study.hibernate.domain.Order */ insert into db_hibernate.tb_order (addr, totalprice, tb_user_id) values (?, ?, ?) // Hibernate: /* insert com.study.hibernate.domain.Order */ insert into db_hibernate.tb_order (addr, totalprice, tb_user_id) values (?, ?, ?) // Hibernate: /* create one-to-many row com.study.hibernate.domain.TbUser.orders */ update db_hibernate.tb_order set tb_user_id=? where id=? // Hibernate: /* create one-to-many row com.study.hibernate.domain.TbUser.orders */ update db_hibernate.tb_order set tb_user_id=? where id=? }
2)级联查询
/** * 多对一查询 */ @Test public void queryTest2(){ Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); String hql = "from Order o where o.id=1"; Query query = session.createQuery(hql); Order o = (Order) query.uniqueResult(); System.out.println(o); transaction.commit(); session.close(); sessionFactory.close(); //结果 // Hibernate: /* from Order o where o.id=1 */ select order0_.id as id1_0_, order0_.addr as addr2_0_, order0_.totalprice as totalpri3_0_, order0_.tb_user_id as tb_user_4_0_ from db_hibernate.tb_order order0_ where order0_.id=1 // Hibernate: /* load com.study.hibernate.domain.TbUser */ select tbuser0_.id as id1_1_0_, tbuser0_.name as name2_1_0_, tbuser0_.age as age3_1_0_, tbuser0_.city as city4_1_0_ from db_hibernate.tb_user tbuser0_ where tbuser0_.id=? // Order [id=1, addr=sjz, totalprice=100, user=TbUser [id=12, name=wangliu, age=12, city=bj]] }
/** * 一对多查询 */ //@Test public void queryTest3(){ Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); String hql = "from TbUser t where t.id=12"; Query query = session.createQuery(hql); TbUser t = (TbUser) query.uniqueResult(); System.out.println(t); Iterator<Order> it =t.getOrders().iterator(); while (it.hasNext()) { System.out.println(it.next()); } transaction.commit(); session.close(); sessionFactory.close(); //结果 // Hibernate: /* from TbUser t where t.id=12 */ select tbuser0_.id as id1_1_, tbuser0_.name as name2_1_, tbuser0_.age as age3_1_, tbuser0_.city as city4_1_ from db_hibernate.tb_user tbuser0_ where tbuser0_.id=12 // TbUser [id=12, name=wangliu, age=12, city=bj] // Hibernate: /* load one-to-many com.study.hibernate.domain.TbUser.orders */ select orders0_.tb_user_id as tb_user_4_1_1_, orders0_.id as id1_0_1_, orders0_.id as id1_0_0_, orders0_.addr as addr2_0_0_, orders0_.totalprice as totalpri3_0_0_, orders0_.tb_user_id as tb_user_4_0_0_ from db_hibernate.tb_order orders0_ where orders0_.tb_user_id=? // Order [id=2, addr=shanghai, totalprice=211, user=TbUser [id=12, name=wangliu, age=12, city=bj]] // Order [id=1, addr=sjz, totalprice=100, user=TbUser [id=12, name=wangliu, age=12, city=bj]] }
3)级联删除
<set name="orders" cascade="delete">
/** * 级联删除操作 */ @Test public void deleteTest2(){ Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); TbUser u = new TbUser(); u.setId(21L); session.delete(u); transaction.commit(); session.close(); sessionFactory.close(); //结果 // Hibernate: /* delete one-to-many com.study.hibernate.domain.TbUser.orders */ update db_hibernate.tb_order set tb_user_id=null where tb_user_id=? // Hibernate: /* delete com.study.hibernate.domain.TbUser */ delete from db_hibernate.tb_user where id=? }
结果: 客户被删除客户所对应的订单的关联ID被设置为NULL。
4)孤子删除
<set name="orders" cascade="delete-orphan">
/** * 级联删除操作--孤子删除 */ //@Test public void deleteTest3(){ Configuration configuration = new Configuration().configure(); ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry(); SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); TbUser u = (TbUser) session.get(TbUser.class, 22L); Order o1 = (Order) session.get(Order.class,new Long(21)); //Order o2 = new Order(); u.getOrders().remove(o1); //session.delete(u); transaction.commit(); session.close(); sessionFactory.close(); //结果 // Hibernate: /* load com.study.hibernate.domain.Order */ select order0_.id as id1_0_0_, order0_.addr as addr2_0_0_, order0_.totalprice as totalpri3_0_0_, order0_.tb_user_id as tb_user_4_0_0_ from db_hibernate.tb_order order0_ where order0_.id=? // Hibernate: /* delete one-to-many com.study.hibernate.domain.TbUser.orders */ update db_hibernate.tb_order set tb_user_id=null where tb_user_id=? // Hibernate: /* delete com.study.hibernate.domain.TbUser */ delete from db_hibernate.tb_user where id=? //当cascade="delete-orphan" //u.getOrders().remove(o1); //结果 // Hibernate: /* load com.study.hibernate.domain.TbUser */ select tbuser0_.id as id1_1_0_, tbuser0_.name as name2_1_0_, tbuser0_.age as age3_1_0_, tbuser0_.city as city4_1_0_ from db_hibernate.tb_user tbuser0_ where tbuser0_.id=? // Hibernate: /* load com.study.hibernate.domain.Order */ select order0_.id as id1_0_0_, order0_.addr as addr2_0_0_, order0_.totalprice as totalpri3_0_0_, order0_.tb_user_id as tb_user_4_0_0_ from db_hibernate.tb_order order0_ where order0_.id=? // Hibernate: /* load one-to-many com.study.hibernate.domain.TbUser.orders */ select orders0_.tb_user_id as tb_user_4_1_1_, orders0_.id as id1_0_1_, orders0_.id as id1_0_0_, orders0_.addr as addr2_0_0_, orders0_.totalprice as totalpri3_0_0_, orders0_.tb_user_id as tb_user_4_0_0_ from db_hibernate.tb_order orders0_ where orders0_.tb_user_id=? // Hibernate: /* delete one-to-many row com.study.hibernate.domain.TbUser.orders */ update db_hibernate.tb_order set tb_user_id=null where tb_user_id=? and id=? // Hibernate: /* delete com.study.hibernate.domain.Order */ delete from db_hibernate.tb_order where id=? }
原始数据:
删除后数据: