简体   繁体   中英

How to properly update entities using REST and JPA/Hibernate

I have entity Document, which has lots of columns, one-to-one, one-to-many and many-to-many mappings to some other entities.

Example:

Document:
  id,
  title,
  body,
  authors,
  viewers,
  ...

Using REST, I want to update some particular document, controller receives serialized Document object, calling EntityManager's merge method persists null results to the database if controller received for instance only body , then I want the body to be updated only, but merge deletes records for title, authors and viewers and etc.

I understand that it is a standard behavior of EntityManager, but I am asking what is the most preferred technique to do updates on entities without receiving whole entity from front-end or some other endpoint. Should I load the entity from database using the id I received and set MANUALLY all of the fields and then save to database or should I use another technique.

I don't have any problem with writing manually all of the setters to copy the changes, but entities are really big in size with lots of relations. Asking for best practice in this case.

I know about DTOs but I want alternate approach when using entities for controllers and service methods.

对于实体部分更新,您将需要使用标准 api 或 jpql ...再次....您还可以将updatable=false用于只应在创建时设置的列(如 CREATION_DATE),并且休眠中还有一个不错的功能,称为@DynamicUpdate ,我没有尝试过,但看起来很棒.. . 它只更新修改后的字段( 在此处查看 Vlad 的帖子)...关于 DTO DP,如果您想隐藏/修改客户端的某些数据,无论您存储数据的方式如何.. . 并且它始终是分离关注点的好方法(但伴随着域和 DTO 对象之间的映射问题,这要归功于spring 转换器

There are two options one is update query, which works fine but you may feel you are loosing some hibernate features and simplicity of the code. Else you can do it in Hibernate way like below

   AuditorBean auditorBean = (AuditorBean) session.get(AuditorBean.class, AuditorBean.getId());
    auditorBean.setFirstName("aa");
    auditorBean.setLatName("bb");
    auditorBean.setTrainLevel("ISO");
    auditorBean.setAccessLevel(4);

Here you should not call any method like saveOrUpdate() or merge(). object is attached with transaction, so object is flushed and committed at the end of the transaction automatically .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM