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
推荐阅读
-
Django之Mode的外键自关联和引用未定义的Model方法
-
关系型数据库的外键约束与关联
-
oracle查询所有用户表的表名、主键名称、索引、外键、修改密码等操作详解
-
sql语句创建外键关联的完整实例
-
mysql-请问数据库表中可以在一个表里面有两个关联同一个表的外键吗?
-
Django之Mode的外键自关联和引用未定义的Model方法
-
MYSQL外键(Foreign Key)的使用--修改(增加)外键方法,外键名不_MySQL
-
mysql的外键多字段关联添加,也叫多外键?这名称怎么说~呵呵_MySQL
-
删除数据库的外键关联
-
MYSQL外键(Foreign Key)的使用--修改(增加)外键方法,外键名不_MySQL