Michele Da Ros
Michele Da Ros

Reputation: 906

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

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)?

Upvotes: 4

Views: 6136

Answers (2)

xenteros
xenteros

Reputation: 15842

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.

Upvotes: 4

Peter Walser
Peter Walser

Reputation: 15706

How is the tenant id set? It's obviously not generated (according to the JPA annotations), so I suppose you set it manually?

If you don't set it at all, the tenantID will be null, thus when inserting another tenant (which then also has tenantID null), the unique constraint will be violated.

Upvotes: 0

Related Questions