简体   繁体   中英

Update entity in jpa

How can I update every fields in Entity without write sql query:

(update Entity u set u.m1= ?1, u.m2= ?2, ... where u.id = ?3)

Class has 20+ fields and if I write sql query This will take a long time. And I often add new fields

Can I update everything automatically? Like this:

entityRepo.update(entity);

If i do entityRepo.save(); create unnecessary record in base.

No, you can use JpaRepository.save(S entity) that saves or updates the entity if existing.
To achieve that, make sure that the entity has its JPA @Id valued before invoking save() otherwise a new record will indeed be created.

This is an alternative to @davidxxx's answer .

If the transaction with which the entity was fetched is not yet closed (ie the entity is still attached), you can simply update the java-object and the changes will be committed to the database when the transaction is committed.

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