J.J. Beam
J.J. Beam

Reputation: 3059

Spring data JPA: How to SELECT, if not found then create?

Are there any concise way in Spring data JPA to perform:

  1. Select a record by a field
  2. If found then return it
  3. If not found then create a new one and return it

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

Answers (1)

Krisz
Krisz

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

Related Questions