Reputation: 670
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
Reputation: 409
Its possible to provide your own extension to the standart spring data repositories:
Adding custom behavior to 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