Yosua Lijanto Binar
Yosua Lijanto Binar

Reputation: 670

Spring JPA Repository - Separate Insert and Update Method

How to create custom method from Spring JPA Repository that separates insert and update functionality? Let's say create method for insert, and update method for update.

Extra question: Why Spring JPA Repository doesn't separate those methods by design?

My current implementation is create validation at Service layer.

My Repository

public interface UserRepository extends CrudRepository<User, Integer> {}

My Service

@Service
public class UserService {
    public void addUser(User user) {
        if (!userRepository.exists(user.getId())) {
            userRepository.save(user);
        }
    }

    public void updateUser(int id, User user) {
        if (userRepository.exists(user.getId())) {
            userRepository.save(user);
        }
    }
}

Upvotes: 7

Views: 14467

Answers (1)

Dudelilama
Dudelilama

Reputation: 409

Its possible to provide your own extension to the standart spring data repositories:

Adding custom behavior to all repositories:

https://docs.spring.io/spring-data/data-commons/docs/current/reference/html/#repositories.custom-behaviour-for-all-repositories

You could for example implement a lock function

void lock(T entity, LockModeType lockModeType);

But in your case, I'd suggest, to just leave the checks away, cause SpringDataRepository already checks if its new or not. If there is an ID, it exists anyway, cause you hopefully don't create your own IDs. It's all part of the spring data contract:

SimpleJpaRepository:

@Transactional
public <S extends T> S save(S entity) {

    if (entityInformation.isNew(entity)) {
        em.persist(entity);
        return entity;
    } else {
        return em.merge(entity);
    }
}

Upvotes: 2

Related Questions