Reputation: 3059
Are there any concise way in Spring data JPA to perform:
atomically?
Does @Transactional
help on this? (I mean create a method, mark it @Transactional
, perform select, if/else inside)
BTW What is the general pure SQL way to solve this problem? (Let's assume MySql DB.)
Upvotes: 0
Views: 1866
Reputation: 2264
There is no pure SQL for what you want to achieve, though you can find vendor-specific solutions. However you can easily achieve this with using Transactional
:
class EntityService {
private final entityRepository;
// constructor omitted
@Transactional
public Entity getOrCreate(Entity entity, Long entityId) {
return entityRepository.findById(entityId)
.orElseGet(() -> entityRepository.save(entity));
}
}
Upvotes: 4