简体   繁体   中英

Multiple updates to the same entity

I have a Hibernate related question . Can I perform multiple saves to a single entity . Do you foresee any problems with this code?

// I create a new object of type Payment that needs to be persisted...

 Payment p1 = new Payment();

//Set some values..

 p1.setName("abc");

//persist it to DB to retrieve the Id which is autogenerated inorder to relay it to another function..

 Payment savedP1 = paymentRepository.save(p1);

 int sum = calPaymentSum(savedP1.getId());

//set more values to the same object ...

 savedP1.setSum(sum);

//update that object that was saved to DB earlier..

 paymentRepository.save(savedP1);

You need to use;

 paymentRepository.update(savedP1);

If you use save method, it is inserted to table with new id.

If you are using spring data jpa repository saving an existing entity will automatically update it and your procedure is right. but in javaEE jpa you need to use merge method of EntityManager in order to update an existing entity.

paymentRepository.merge(savedP1);

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