小编典典

休眠:“字段'id'没有默认值”

java

我面临的问题是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)不能解决问题

求助: 重新创建数据库解决了问题


阅读 222

收藏
2020-09-08

共1个答案

小编典典

有时,即使执行了,对模型或ORM所做的更改也可能无法准确反映在数据库上SchemaUpdate

如果错误实际上似乎缺乏合理的解释,请尝试重新创建数据库(或至少创建一个新数据库)并使用进行构建SchemaExport

2020-09-08