如何在不定义主键字段的情况下使用实体管理器插入记录?
发布时间:2020-12-15 02:34:22 所属栏目:Java 来源:网络整理
导读:我试图使用实体类和实体管理器将记录插入数据库( MySQL).但其中一个字段是自动递增主键,因此除非我手动提供值,否则插入不成功. public boolean newContributor(String name,String email,String country,Integer contactable,String address) { Contributors
我试图使用实体类和实体管理器将记录插入数据库(
MySQL).但其中一个字段是自动递增主键,因此除非我手动提供值,否则插入不成功.
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; } 怎么解决这个问题?有没有办法告诉实体管理器尝试没有ID字段的插入,而是使用NULL值. 更新:这是定义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) .... 解决方法
当然.您需要在@Entity定义中删除id字段的@NotNull注释,并删除该行: contributor.setId(??????); 来自方法newContributor().原因是@NotNull注释在JPA堆栈中强制执行验证检查.这并不意味着该字段在数据库级别为NOT NULL.请参阅here关于此问题的讨论. 其余的代码看起来很好. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |