Spring Data JPA save only if doesnt exist

Viewed 5750

I found a code in project. It looks like:

private <S, T extends BaseEntity<S>> void saveIfNotExist(T baseEntity, JpaRepository<T, S> jpaRepository) {
        jpaRepository
                .findById(baseEntity.getId())
                .orElseGet(() -> jpaRepository.save(baseEntity));
}

As far as i understand, this method will not save/update entity in database, if entity already exists.

BaseEntity:

public interface BaseEntity<T> {
    T gettId();
}

Implementation:

@Entity
@Table(..)
public class Account implements BaseEntity<String> {

    @Id
    private String login;
    
    @Column(name = "is_archive")
    private Boolean isArchive;
   

    public String getId() {
        return this.getLogin();
    }
}

Repository:

@Repository
public interface AccountRepository extends JpaRepository<Account, Integer>

My question is: how can i replace this method with common Spring Data JPA realisation (save only if not exists, don't update)?

0 Answers
Related