[英]How to insert records using the Entity Manager without defining the Primary Key field?
I have trying to insert a record into the database (MySQL), using Entity Class and Entity Manager. 我试图使用实体类和实体管理器将记录插入数据库(MySQL)。 But one of the field is an auto incrementing primary key, so unless I provide an value manually, the insertion is not successful.
但其中一个字段是自动递增主键,因此除非我手动提供值,否则插入不成功。
public boolean newContributor(String name, String email, String country, Integer contactable, String address) {
Contributors contributor = new Contributors(); //entity class
contributor.setId(??????); //this is Primary Key field and is of int datatype
contributor.setName(name);
contributor.setEmail(email);
contributor.setCountry(country);
contributor.setContactable(contactable);
contributor.setAddress(address);
em.persist(contributor);
return true;
}
How to solve such problem? 怎么解决这个问题? Is there a way to tell the entity manager to attempt the insert without the ID field and use
NULL
value instead. 有没有办法告诉实体管理器尝试没有ID字段的插入,而是使用
NULL
值。
Update: Here is a portion of the entity class defining the id
更新:这是定义
id
的实体类的一部分
...
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@NotNull
@Column(name = "id")
private Integer id;
@Basic(optional = false)
@NotNull
@Size(min = 1, max = 50)
....
Is there a way to tell the entity manager to attempt the insert without the ID field and use NULL value instead?
有没有办法告诉实体管理器尝试插入没有ID字段并使用NULL值代替?
Sure. 当然。 You need to remove the
@NotNull
annotation for id
field in the @Entity
definition, and also remove the row: 您需要在
@Entity
定义中删除id
字段的@NotNull
注释,并删除该行:
contributor.setId(??????);
from method newContributor()
. 来自方法
newContributor()
。 The reason for this is that the @NotNull
annotation enforces a validation check in the JPA stack. 原因是
@NotNull
注释在JPA堆栈中强制执行验证检查。 It doesn't mean that the field is NOT NULL at a database level. 这并不意味着该字段在数据库级别为NOT NULL。 See here a discussion about this issue.
请参阅此处有关此问题的讨论。
The rest of the code looks fine. 其余的代码看起来很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.