Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: primary key violation when saving an entity with many to one

Tags:

java

jpa

I have 2 JPA Entities

@Entity
@Data
public class Config {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String data;

    @ManyToOne(cascade= CascadeType.ALL)
    private Tenant tenant;
}


@Entity
@AllArgsConstructor
class Tenant {  
    @Id
    private String tenantID;
}

and a repository

interface SolmanConfigPrivateRepository extends CrudRepository <Config, Long> {

}

I create new entities with the following code

public void addConfig(Config config){
    String tenantId = userProvider.get();
    config.setTenant(getCurrentTenant());
    Tenant tenant = new Tenant(tenantId);
    dbRepository.save(config);

}

I manage to save a Config using the save method of the repository.

If I try to save a new Config with the same tenant, I get an error

 Unique index or primary key violation: "PRIMARY_KEY_9 ON PUBLIC.TENANT(TENANTID)

How can I tell JPA to not try to create a new Tenant if there is already another one in the database (but to reference the existing one instead)?

like image 331
Michele Da Ros Avatar asked Sep 13 '25 23:09

Michele Da Ros


1 Answers

You're violating hibernate session. What you have to do, is to find Tenant from db by id, set entity picked up from the db (that certain reference) and then save. Otherwise, Hibernate will try to save instead of update.

public void addConfig(SolManConfig solManConfig){
    String tenantId = userProvider.get();
    solManConfig.setTenant(getCurrentTenant());
    Tenant tenant = tentantRepository.findOne(tenantId);
    dbRepository.save(solManConfig);
}

Spring data JPA has one method for save and update. It's save. When you pass a new object, it saves, otherwise it updates. What does it mean 'new object'? It means, an object which hasn't been extracted from the db.

like image 58
xenteros Avatar answered Sep 15 '25 12:09

xenteros