休眠:“字段‘id’没有默认值"; [英] Hibernate: "Field 'id' doesn't have a default value"

查看:35
本文介绍了休眠:“字段‘id’没有默认值";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正面临着我认为 Hibernate 的一个简单问题,但无法解决它(无法访问 Hibernate 论坛当然无济于事).

I'm facing what I think is a simple problem with Hibernate, but can't solve it (Hibernate forums being unreachable certainly doesn't help).

我有一个简单的课程,我想坚持下去,但要继续:

I have a simple class I'd like to persist, but keep getting:

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 ]

持久化类的相关代码为:

The relevant code for the persisted class is:

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;
    }
}

实际运行的代码很简单:

And the actual running code is just plain:

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).

I tried some "strategies" within the GeneratedValue annotation but it just doesn't seem to work. Initializing id doesn't help either! (eg Long id = 20L).

有人能解释一下吗?

EDIT 2: 确认:使用@GeneratedValue(strategy = GenerationType.XXX) 并不能解决问题

EDIT 2: confirmed: messing with@GeneratedValue(strategy = GenerationType.XXX) doesn't solve it

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

SOLVED: recreating the database solved the problem

推荐答案

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

Sometimes changes made to the model or to the ORM may not reflect accurately on the database even after an execution of SchemaUpdate.

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

If the error actually seems to lack a sensible explanation, try recreating the database (or at least creating a new one) and scaffolding it with SchemaExport.

这篇关于休眠:“字段‘id’没有默认值";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆