Skip to content
Advertisement

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

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

@Override
public void persistOrder(final Order order) {
    orderRepository.save(order);
}

and my repository:

@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:

@Override
public void saveOrUdpate(final Order order) {
  orderRepository.save(order);
  long id = orderRepository.findByOrderId(order.get()).getId();
  orderRepository.deleteById(id);
  orderRepository.save(order);
}

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 🙂

Advertisement

Answer

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

 @Override
 public void updateOrder(Order order) {
    long id = orderRepository.findByOrderId(order.get().getId());
    order.setId(id);
    orderRepository.save(order);
}

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!

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement