如果主键不为空,Spring 数据 JPA 不允许实体持久化 [英] Spring data JPA does not allow an Entity to be peristed if the primary key is not null

查看:23
本文介绍了如果主键不为空,Spring 数据 JPA 不允许实体持久化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个订阅者实体,它使用用户提供的电子邮件地址作为主键,而不是自动生成的值.这意味着调用JpaRepository的save方法时,主键值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 数据 JPA 文档 第 2.2.1 节表 2.2 说明如下:

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

默认情况下,Spring Data JPA 检查给定的 Id-Property实体.如果 Id-Property 为 null,则实体将被假定为新的,否则就不是新的.

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.

推荐答案

在决定如何选择实体的主键时,我们有两个选择.1.使用Spring提供的自动生成的key2. 使用自定义主键,例如一个电子邮件地址.

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, e.g. an email address.

自动生成的密钥使用起来更简单.在持久化实体时,Spring 注意到 id 字段为空并得出结论,这是一个新的实体被持久化.一个新的自动生成的值被分配给 id 字段并且实体被持久化.但是,如果您想确保不保留具有相同电子邮件地址的两个实体,请记住使用 @Column(unique="true") 注释电子邮件字段.由于电子邮件字段的唯一约束,检测重复项也很容易.

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.

但是,有时您不想使用自动生成的密钥,因为您可能希望使用用户提供的电子邮件地址作为密钥.这种方法没有问题.使用@Id 标记实体中的电子邮件字段.仅此而已.但是,无法进行重复检测.如果多次收到创建具有相同电子邮件地址的实体的请求,则每次都会更新相同的实体,即每次都会执行 EntityManager.merge().不会引发约束违反异常.回想一下,Spring 总是检查主键字段是否为空来决定是创建新实体还是合并到现有实体中.

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, i.e. 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.

这篇关于如果主键不为空,Spring 数据 JPA 不允许实体持久化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆