Update entity if already exists or create using spring jpa

13,046

Solution 1

Add in your Transaction Entity on variable called name this for naming as unique:

  @Entity
  public class Transaction {
      ...
      @Column(name="name", unique=true)
      private String name;
      ... 
  } 

Then you won't be able to add duplicate values for name column.

Solution 2

First, this is from google composite key means

A composite key is a combination of two or more columns in a table that can be used to uniquely identify each row in the table when the columns are combined uniqueness is guaranteed, but when it taken individually it does not guarantee uniqueness.

A composite key with an unique key is a waste.

if you want to update an entity by jpa, you need to have an key to classify if the entity exist already.

    @Transactional
public <S extends T> S save(S entity) {
    if(this.entityInformation.isNew(entity)) {
        this.em.persist(entity);
        return entity;
    } else {
        return this.em.merge(entity);
    }
}

There are two ways to handle your problem.

If you can not get id from client on updating, it means that id has lost its original function. Then remove your the annotation @Id on your id field,set name with @Id. And do not set auto generate for it.

I think what you want is an @Column(unique = true,nullable = false) on your name field. And that is the order to update something.

Transaction t = transactionRepository.findByName(name);
t.set.... //your update
transactionRepository.save(t);
Share:
13,046
Rocky4Ever
Author by

Rocky4Ever

Updated on June 28, 2022

Comments

  • Rocky4Ever
    Rocky4Ever almost 2 years

    I am new to spring data jpa. I have a scenario where I have to create an entity if not exists or update based on non primary key name.Below is the code i wrote to create new entity,it is working fine,but if an already exists record ,its creating duplicate.How to write a method to update if exists ,i usually get list of records from client.

    @Override
    @Transactional
    public String createNewEntity(List<Transaction> transaction) {
    
       List<Transaction> transaction= transactionRespository.saveAll(transaction);
    }