我认为 Hibernate 面临的问题很简单,但却无法解决(Hibernate 论坛无法访问肯定没有帮助)。
我有一个简单的类,我想坚持下去,但不断得到:
SEVERE: Field 'id' doesn't have a default value
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not insert: [hibtest.model.Mensagem]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
[ a bunch more ]
Caused by: java.sql.SQLException: Field 'id' doesn't have a default value
[ a bunch more ]
持久化类的相关代码是:
package hibtest.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
public class Mensagem {
protected Long id;
protected Mensagem() { }
@Id
@GeneratedValue
public Long getId() {
return id;
}
public Mensagem setId(Long id) {
this.id = id;
return this;
}
}
实际的运行代码很简单:
SessionFactory factory = new AnnotationConfiguration()
.configure()
.buildSessionFactory();
{
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Mensagem msg = new Mensagem("YARR!");
session.save(msg);
tx.commit();
session.close();
}
我在 GeneratedValue
注释中尝试了一些“策略”,但它似乎不起作用。初始化 id
也没有帮助!(例如 Long id = 20L
)。
有人能透露点消息吗?
编辑2: 确认: 干扰 @GeneratedValue(strategy = GenerationType.XXX)
并不能解决问题
重建数据库解决了这个问题