JPA modifies the entity class associated with the foreign key

Case 1: Do not update the foreign key id, update the entity object associated with the foreign key (it is not allowed to set the id of the foreign key entity associated object)

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);

Case 2: To update the foreign key id, a new foreign key associated object needs to be instantiated. The object associated with the original foreign key must not be modified. If it is modified, the following comments must be deleted.

RestaurantDto restaurantDto = restaurantDao.getByUserId(userId);  
LocationDto location = new LocationDto(restaurant.getLocation());  
location.setConnPerson(restaurantDto.getPrincipal());  
location.setConnPhone(userDto.getPhone());  
 //locationDao.returnentityManager().clear(); If the entity associated with the original foreign key is modified, clear must be used to save the new entity
locationDao.returnentityManager().persist(location);// You cannot use merge here. For a new object, merge just turns it into a managed state, and the following statement is associated with the object, so it must be persisted first  
restaurantDto.setLocation(location);  
restaurantDao.returnEntityManager().merge(restaurantDto); 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324678513&siteId=291194637