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.

Upvotes: 2

Views: 170

Answers (2)

Turing85
Turing85

Reputation: 20185

This is an alternative to @davidxxx's answer.

If the transaction with which the entity was fetched is not yet closed (i.e. 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.

Upvotes: 2

davidxxx
davidxxx

Reputation: 131326

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.

Upvotes: 2

Related Questions