jpa级联操作详解5-级联更新2(CascadeType.MERGE)
程序员文章站
2022-05-01 23:18:26
...
在上一讲中我们看到两次发出的sql语句是一样的,也就是说两种情况对数据库的操作是一样的,为什么会这样呢?
主要是由于,级联更新在实体是游离状态下才起作用现在依然使用上一讲的实体bean;
第一次在Garage.java 不添加CascadeType.MERGE注解
@OneToMany(cascade={CascadeType.PERSIST},mappedBy="garage")
public Set<Auto> getAutos() {
return autos;
}
重新编写单元测试方法
@Test public void update() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("jpa-hibernate");
EntityManager em = factory.createEntityManager();
em.getTransaction().begin();
Garage garage = em.find(Garage.class, 1);
em.clear(); //改为游离状态
garage.setGaragenum("RoomTOP");
em.merge(garage);
em.getTransaction().commit();
em.close();
factory.close();
}
运行之后
观察发出的sql语句
Hibernate: select garage0_.gid as gid1_0_, garage0_.garagenum as garagenum1_0_ from Garage garage0_ where garage0_.gid=?
Hibernate: select garage0_.gid as gid1_0_, garage0_.garagenum as garagenum1_0_ from Garage garage0_ where garage0_.gid=?
Hibernate: update Garage set garagenum=? where gid=?
(二)添加CascadeType.MERGE注解
@OneToMany(cascade={CascadeType.PERSIST,CascadeType.MERGE},mappedBy="garage")
public Set<Auto> getAutos() {
return autos;
}
运行单元测试方法update()
观察发出的sql语句
Hibernate: select garage0_.gid as gid1_0_, garage0_.garagenum as garagenum1_0_ from Garage garage0_ where garage0_.gid=?
Hibernate: select garage0_.gid as gid1_1_, garage0_.garagenum as garagenum1_1_, autos1_.garageid as garageid3_, autos1_.autoId as autoId3_, autos1_.autoId as autoId0_0_, autos1_.autonum as autonum0_0_, autos1_.autotype as autotype0_0_, autos1_.garageid as garageid0_0_ from Garage garage0_ left outer join Auto autos1_ on garage0_.gid=autos1_.garageid where garage0_.gid=?
Hibernate: update Garage set garagenum=? where gid=?
比较第一次和第二次发出的sql语句,第二次是做外连接
上一篇: Spring学习笔记(一)配置文件的使用
下一篇: js中的数组操作