【发布时间】:2014-05-31 00:30:05
【问题描述】:
我在 Mysql 中使用 spring jpa。
我正在尝试实现以下解决方案来绕过生成的 id 字段:Bypass GeneratedValue in Hibernate (merge data not in db?)
问题是当 id 为 null 并且应该生成时,我得到:“字段 'id' 没有默认值”
我的实体:
@Entity
public class RegistrationDetails{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY, generator = "IdOrGenerated")
@GenericGenerator(name = "IdOrGenerated", strategy = "com.xxx.common.UseIdOrGenerate")
@Column(name = "ID", nullable = false)
private Long id;
@Column(nullable = false)
private String firstName;
}
我的发电机:
public class UseIdOrGenerate extends IdentityGenerator {
@Override
public Serializable generate(SessionImplementor session, Object obj) throws HibernateException {
if (obj == null)
throw new HibernateException(
new NullPointerException());
if ((((RegistrationDetails) obj).getId()) == null) {
Serializable id = super.generate(
session,
obj);
return id;
}
else {
return ((RegistrationDetails) obj).getId();
}
}
}
从一些对话中,我认为它与自动增量有关,但我无法在 MySql 中添加它。
编辑: 我的表是在 tomcat 服务器启动时自动生成的。问题是它没有将 id 字段设置为自动增量。这个有hibernate注解吗?
【问题讨论】:
-
创建表时是否自动生成
-
tomcat服务器启动时生成的表,有jpa注解吗? GenerationType.auto 不起作用
-
当我在 mysql 工作台中手动尝试时出现错误
-
你能给出错误吗?你用em.persist保存了吗
-
错误:无法更改列“ID”:用于外键约束。我正在使用 jpa 存储库进行保存
标签: java mysql spring hibernate jpa