How can I implement a Save Or Update function using Spring Data Jpa?

Tags: , , , ,

I am using Spring Data JPA to save a record to my database. Here is the method I am using:

public void persistOrder(final Order order) {;

and my repository:

public interface OrderRepository extends JpaRepository<Order, Long> {
    Optional<Order> findByOrderId(UUID orderId);

I want to modify this so it will Save or Update. This is what I have so far:

public void saveOrUdpate(final Order order) {;
  long id = orderRepository.findByOrderId(order.get()).getId();

I have a few questions –
#1 Is this bad practice (deleting and then re-inserting)?
#2 If I implement my repo using hibernate, would a hibernate saveOrUpdate(..) do the same thing under the hood?
#3 Do you have an idea how I can achieve this just using plain Spring Data Jpa?

Thanks 🙂


Ok, thanks for the comments, I’ve decided to add a separate update method! I think this is looking better!

 public void updateOrder(Order order) {
    long id = orderRepository.findByOrderId(order.get().getId());

A good point was made about Spring Data JPA’s save(..) method doing an upsert by default. But, unfortunately in the project I’m working on the primary keys are autogenerated. This means that whenever save(..) is executed on an existing record to update it, a new record is created instead! That’s why I explicitly set the id here to avoid that happening!

I’ve also added and eclipse-link library @Index annotation to the orderId column (not primary key) in the entity class to speed up the update method’s findByOrderId!

Source: stackoverflow