欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JPA修改外键关联的实体类

程序员文章站 2022-04-21 10:13:17
...

情况一: 不update外键id, update外键关联的实体对象(不允许设置外键实体关联对象的id)

 

RestaurantDto restaurantDto = restaurantDao.getByUserId(userId);
restaurantDto.getLocation().setName(restaurant.getName());
restaurantDto.getLocation().setConnPerson(restaurant.getPrincipal());
restaurantDto.getLocation().setPointX(restaurant.getLocation().getPointX());
restaurantDto.getLocation().setPointY(restaurant.getLocation().getPointY());
restaurantDto.setName(restaurant.getName());
restaurantDto.setPrincipal(restaurant.getPrincipal());
restaurantDao.returnEntityManager().merge(restaurantDto);

 

情况二: update外键id, 需要实例化一个新的外键关联对象, 原有外键关联的对象绝不允许修改, 如果修改了必须把下面的注释干掉

 

RestaurantDto restaurantDto = restaurantDao.getByUserId(userId);  
LocationDto location = new LocationDto(restaurant.getLocation());  
location.setConnPerson(restaurantDto.getPrincipal());  
location.setConnPhone(userDto.getPhone());  
 //locationDao.returnentityManager().clear();  如果原外键关联的实体修改,必须使用clear后才能保存新new的实体
locationDao.returnentityManager().persist(location);
//location = locationDao.returnentityManager().merge(location); 如果使用merge替换persist, 必须对location重新赋值
restaurantDto.setLocation(location);  
restaurantDao.returnEntityManager().merge(restaurantDto); 

1. hql查询得到的数据封装到对象中,对象会放入一级缓存嘛(再次查询不会使用缓存,但是修改会保存到db)

2. 通过关联查询时(如A外键关联B), A和B都放入到一级缓存中, 只要A和B中的任一字段修改, 都会在事务提交时做update操作.

(1)jpa不允许一级缓存中的对象的主键id被修改

(2)级联保存时, 可以设置A和B的关联关系, 直接保存A即可. 而在对A的外键关联的B做实体级别的替换时(即先查出A,然后修改

A的外键), 必须先new 一个新的B实体, 并对B持久化(或者说将B实体由瞬态变为托管态)

3. persist()和merge的区别: https://blog.csdn.net/asdfsadfasdfsa/article/details/80042077