简体   繁体   中英

Spring data JPA does not allow an Entity to be peristed if the primary key is not null

I have a Subscriber Entity which uses a user supplied email address as the primary key rather than an auto-generated value. This means that when the save method of the JpaRepository is called, the primary key value is not null .

Spring data JPA documentation section 2.2.1 table 2.2 says the following:

By default Spring Data JPA inspects the Id-Property of the given Entity. If the Id-Property is null, then the entity will be assumed as new, otherwise as not new.

This behaviour prevents a new Subscriber entity from being persisted to the database.

When it comes to deciding how to select the primary key of an entity, we have two options. 1. Use the auto-generated key provided by Spring 2. Use a custom primary key, eg an email address.

The auto generated key is simpler to use. When persisting the entity, Spring notices that the id field is empty and concludes that this a new entity being persisted. A new auto-generated value is assigned to the id field and the entity is persisted. However, if you want to ensure that two entities with the same email address are not persisted, remember to annotate the email field with @Column(unique="true") . Detecting duplicates is also easy because of the unique constraint on the email field.

However, sometimes you don't want to use the auto-generated key because you may want to use a user provided email address as the key. There is no problem with this approach. Mark the email field in the entity with the @Id. That's all. However, duplicate detection is not possible. If a request to create an entity with the same email address is received multiple times, the same entity will be updated each time, ie EntityManager.merge() will be done each time. A constraint violation exception will not be raised. Recall, Spring always checks whether the primary key field is empty or not to decide whether to create a new entity or merge into an existing entity.

The same table tells you how to customize that behavior.

Either let your entity implement Persistable and overwrite isNew , or provide a custom implementation of EntityInformation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM