Java 休眠:“字段‘id’没有默认值”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/804514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 19:39:42  来源:igfitidea点击:

Hibernate: "Field 'id' doesn't have a default value"

javahibernatejpapersistence

提问by André Chalella

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

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

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

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

我在GeneratedValue注释中尝试了一些“策略”,但似乎不起作用。初始化id也无济于事!(例如Long id = 20L)。

Could anyone shed some light?

有人能解释一下吗?

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

编辑 2:确认: 弄乱@GeneratedValue(strategy = GenerationType.XXX)并不能解决它

SOLVED:recreating the database solved the problem

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

采纳答案by André Chalella

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

有时,即使在执行SchemaUpdate.

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.

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

回答by Steve Kuo

Take a look at GeneratedValue's strategy. It typically looks something like:

看看GeneratedValue的策略。它通常看起来像:

@GeneratedValue(strategy=GenerationType.IDENTITY)

回答by tarhack

Add a method hashCode()to your Entity Bean Class and retry it

hashCode()向您的实体 Bean 类添加一个方法并重试

回答by Arun

Please check whether the Default value for the column id in particular table.if not make it as default

请检查特定表中列 id 的默认值是否设置为默认值。

回答by Greg Keyes

If you want MySQL to automatically produce primary keys then you have to tell it when creating the table. You don't have to do this in Oracle.

如果您希望 MySQL 自动生成主键,那么您必须在创建表时告诉它。您不必在 Oracle 中执行此操作。

On the Primary Key you have to include AUTO_INCREMENT. See the example below.

在主键上,您必须包含AUTO_INCREMENT. 请参阅下面的示例。

CREATE TABLE `supplier`  
(  
  `ID` int(11) NOT NULL **AUTO_INCREMENT**,  
  `FIRSTNAME` varchar(60) NOT NULL,  
  `SECONDNAME` varchar(100) NOT NULL,  
  `PROPERTYNUM` varchar(50) DEFAULT NULL,  
  `STREETNAME` varchar(50) DEFAULT NULL,  
  `CITY` varchar(50) DEFAULT NULL,  
  `COUNTY` varchar(50) DEFAULT NULL,  
  `COUNTRY` varchar(50) DEFAULT NULL,  
  `POSTCODE` varchar(50) DEFAULT NULL,  
  `HomePHONENUM` bigint(20) DEFAULT NULL,  
  `WorkPHONENUM` bigint(20) DEFAULT NULL,  
  `MobilePHONENUM` bigint(20) DEFAULT NULL,  
  `EMAIL` varchar(100) DEFAULT NULL,  
  PRIMARY KEY (`ID`)  
) 

ENGINE=InnoDB DEFAULT CHARSET=latin1;  

Here's the Entity

这是实体

package com.keyes.jpa;  

import java.io.Serializable;
import javax.persistence.*;
import java.math.BigInteger;

/**
 * The persistent class for the parkingsupplier database table.
 * 
 */
@Entity
@Table(name = "supplier")
public class supplier implements Serializable
{
  private static final long serialVersionUID = 1L;

  @Id
  **@GeneratedValue(strategy = GenerationType.IDENTITY)**
  @Column(name = "ID")
  private long id;

  @Column(name = "CITY")
  private String city;

  @Column(name = "COUNTRY")
  private String country;

  @Column(name = "COUNTY")
  private String county;

  @Column(name = "EMAIL")
  private String email;

  @Column(name = "FIRSTNAME")
  private String firstname;

  @Column(name = "HomePHONENUM")
  private BigInteger homePHONENUM;

  @Column(name = "MobilePHONENUM")
  private BigInteger mobilePHONENUM;

  @Column(name = "POSTCODE")
  private String postcode;

  @Column(name = "PROPERTYNUM")
  private String propertynum;

  @Column(name = "SECONDNAME")
  private String secondname;

  @Column(name = "STREETNAME")
  private String streetname;

  @Column(name = "WorkPHONENUM")
  private BigInteger workPHONENUM;

  public supplier()
  {
  }

  public long getId()
  {
    return this.id;
  }

  public void setId(long id)
  {
    this.id = id;
  }

  public String getCity()
  {
    return this.city;
  }

  public void setCity(String city)
  {
    this.city = city;
  }

  public String getCountry()
  {
    return this.country;
  }

  public void setCountry(String country)
  {
    this.country = country;
  }

  public String getCounty()
  {
    return this.county;
  }

  public void setCounty(String county)
  {
    this.county = county;
  }

  public String getEmail()
  {
    return this.email;
  }

  public void setEmail(String email)
  {
    this.email = email;
  }

  public String getFirstname()
  {
    return this.firstname;
  }

  public void setFirstname(String firstname)
  {
    this.firstname = firstname;
  }

  public BigInteger getHomePHONENUM()
  {
    return this.homePHONENUM;
  }

  public void setHomePHONENUM(BigInteger homePHONENUM)
  {
    this.homePHONENUM = homePHONENUM;
  }

  public BigInteger getMobilePHONENUM()
  {
    return this.mobilePHONENUM;
  }

  public void setMobilePHONENUM(BigInteger mobilePHONENUM)
  {
    this.mobilePHONENUM = mobilePHONENUM;
  }

  public String getPostcode()
  {
    return this.postcode;
  }

  public void setPostcode(String postcode)
  {
    this.postcode = postcode;
  }

  public String getPropertynum()
  {
    return this.propertynum;
  }

  public void setPropertynum(String propertynum)
  {
    this.propertynum = propertynum;
  }

  public String getSecondname()
  {
    return this.secondname;
  }

  public void setSecondname(String secondname)
  {
    this.secondname = secondname;
  }

  public String getStreetname()
  {
    return this.streetname;
  }

  public void setStreetname(String streetname)
  {
    this.streetname = streetname;
  }

  public BigInteger getWorkPHONENUM()
  {
    return this.workPHONENUM;
  }

  public void setWorkPHONENUM(BigInteger workPHONENUM)
  {
    this.workPHONENUM = workPHONENUM;
  }

}

回答by Eric

I had the same problem. I was using a join table and all I had with a row id field and two foreign keys. I don't know the exact caused but I did the following

我有同样的问题。我正在使用连接表,并且我拥有一个行 ID 字段和两个外键。我不知道确切的原因,但我做了以下

  1. Upgraded MySQL to community 5.5.13
  2. Rename the class and table
  3. Make sure I had hashcode and equals methods

    @Entity 
    @Table(name = "USERGROUP")
    public class UserGroupBean implements Serializable {
    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "USERGROUP_ID")
    private Long usergroup_id;
    
    @Column(name = "USER_ID")   
    private Long user_id;
    
    @Column(name = "GROUP_ID")
    private Long group_id;
    
  1. 将 MySQL 升级到社区 5.5.13
  2. 重命名类和表
  3. 确保我有 hashcode 和 equals 方法

    @Entity 
    @Table(name = "USERGROUP")
    public class UserGroupBean implements Serializable {
    private static final long serialVersionUID = 1L;
    
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name = "USERGROUP_ID")
    private Long usergroup_id;
    
    @Column(name = "USER_ID")   
    private Long user_id;
    
    @Column(name = "GROUP_ID")
    private Long group_id;
    

回答by nize

Another suggestion is to check that you use a valid type for the auto-generated field. Remember that it doesn't work with String, but it works with Long:

另一个建议是检查您对自动生成的字段使用的类型是否有效。请记住,它不适用于 String,但适用于 Long:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
public Long id;

@Constraints.Required
public String contents;

The above syntax worked for generating tables in MySQL using Hibernate as a JPA 2.0 provider.

上述语法适用于使用 Hibernate 作为 JPA 2.0 提供程序在 MySQL 中生成表。

回答by anzie001

you must be using update in your hbm2ddl property. make the changes and update it to Create so that it can create the table.

您必须在 hbm2ddl 属性中使用更新。进行更改并将其更新为 Create 以便它可以创建表。

<property name="hbm2ddl.auto">create</property>

It worked for me.

它对我有用。

回答by Sahan Jayasumana

I came here because of the error message, turns out I had two tables with the same name.

我是因为错误消息来到这里的,结果我有两个同名的表。

回答by user2982704

Just add not-null constraint

只需添加非空约束

I had the same problem. I just added not-null constraint in xml mapping. It worked

我有同样的问题。我刚刚在 xml 映射中添加了非空约束。有效

<set name="phone" cascade="all" lazy="false" > 
   <key column="id" not-null="true" />
   <one-to-many class="com.practice.phone"/>
</set>