How to beautifully update a JPA entity in Spring Data?
Simple JPA update..
Customer customer = em.find(id, Customer.class); //Consider em as JPA EntityManager
customer.setName(customerDto.getName);
em.merge(customer);
Even better then @Tanjim Rahman answer you can using Spring Data JPA use the method T getOne(ID id)
Customer customerToUpdate = customerRepository.getOne(id);
customerToUpdate.setName(customerDto.getName);
customerRepository.save(customerToUpdate);
Is's better because getOne(ID id)
gets you only a reference (proxy) object and does not fetch it from the DB. On this reference you can set what you want and on save()
it will do just an SQL UPDATE statement like you expect it. In comparsion when you call find()
like in @Tanjim Rahmans answer spring data JPA will do an SQL SELECT to physically fetch the entity from the DB, which you dont need, when you are just updating.
This is more an object initialzation question more than a jpa question, both methods work and you can have both of them at the same time , usually if the data member value is ready before the instantiation you use the constructor parameters, if this value could be updated after the instantiation you should have a setter.
In Spring Data you simply define an update query if you have the ID
@Repository
public interface CustomerRepository extends JpaRepository<Customer , Long> {
@Query("update Customer c set c.name = :name WHERE c.id = :customerId")
void setCustomerName(@Param("customerId") Long id, @Param("name") String name);
}
Some solutions claim to use Spring data and do JPA oldschool (even in a manner with lost updates) instead.