我面对的是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)。
GeneratedValue
id
Long id = 20L
谁能给我一些启示?
编辑2: 确认:@GeneratedValue(strategy = GenerationType.XXX)不能解决问题
@GeneratedValue(strategy = GenerationType.XXX)
求助: 重新创建数据库解决了问题
有时,即使执行,对模型或ORM所做的更改也可能无法准确反映在数据库上SchemaUpdate。
SchemaUpdate
如果错误实际上似乎缺乏明智的解释,请尝试重新创建数据库(或至少创建一个新数据库)并使用进行扩展SchemaExport。
SchemaExport