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

JavaHibernateJpaPersistence

Java Problem Overview


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

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

Could anyone shed some light?

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

SOLVED: recreating the database solved the problem

Java Solutions


Solution 1 - Java

Sometimes changes made to the model or to the ORM may not reflect accurately on the database even after an execution of 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.

Solution 2 - Java

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.

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

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

}

Solution 3 - Java

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

@GeneratedValue(strategy=GenerationType.IDENTITY)

Solution 4 - Java

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

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

It worked for me.

Solution 5 - Java

Dropping the table from the database manually and then re-running the application worked for me. In my case table was not created properly(with constraints) I guess.

Solution 6 - Java

I had this issue. My mistake was i had set the insertable and updatable fileds as false and was trying to set the field in the request. This field is set as NON NULL in DB.

@ManyToOne
@JoinColumn(name="roles_id",  referencedColumnName = "id", insertable = false, updatable = false, nullable=false)
@JsonBackReference
private Role role;

Later I changed it to - insertable = true, updatable = true

@ManyToOne
@JoinColumn(name="roles_id",  referencedColumnName = "id", insertable = true, updatable = true, nullable=false)
@JsonBackReference
//@JsonIgnore
private Role role;

It worked perfectly later.

Solution 7 - Java

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

Solution 8 - Java

I had the same problem. I found the tutorial Hibernate One-To-One Mapping Example using Foreign key Annotation and followed it step by step like below:

Create database table with this script:

create table ADDRESS (
   id INT(11) NOT NULL AUTO_INCREMENT,
   street VARCHAR(250) NOT NULL,
   city  VARCHAR(100) NOT NULL,
   country  VARCHAR(100) NOT NULL,
   PRIMARY KEY (id)
);
 
create table STUDENT (
	id            INT(11) NOT NULL AUTO_INCREMENT, 
	name          VARCHAR(100) NOT NULL, 
	entering_date DATE NOT NULL, 
	nationality   TEXT NOT NULL, 
	code          VARCHAR(30) NOT NULL,
	address_id INT(11) NOT NULL,
	PRIMARY KEY (id),
	CONSTRAINT student_address FOREIGN KEY (address_id) REFERENCES ADDRESS (id)   
);

Here is the entities with the above tables

@Entity
@Table(name = "STUDENT")
public class Student implements Serializable {
 
	private static final long serialVersionUID = 6832006422622219737L;
 
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private int id;
 
 }

@Entity
@Table(name = "ADDRESS")
public class Address {

	@Id @GeneratedValue
	@Column(name = "ID")
	private long id;
}

The problem was resolved.

Notice: The primary key must be set to AUTO_INCREMENT

Solution 9 - Java

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:

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

Solution 10 - Java

Just add not-null constraint

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

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

Solution 11 - Java

Maybe that is the problem with the table schema. drop the table and rerun the application.

Solution 12 - Java

In addition to what is mentioned above, do not forget while creating sql table to make the AUTO INCREMENT as in this example

CREATE TABLE MY_SQL_TABLE (

  USER_ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
  FNAME VARCHAR(50) NOT NULL,
  LNAME VARCHAR(20) NOT NULL,
  EMAIL VARCHAR(50) NOT NULL
);

Solution 13 - Java

When your field is not nullable it requires a default value to be specified on table creation. Recreate a table with AUTO_INCREMENT properly initialized so DB will not require default value since it will generate it by itself and never put NULL there.

CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)

);

https://www.w3schools.com/sql/sql_autoincrement.asp

Solution 14 - Java

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

Solution 15 - Java

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

  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;
    

Solution 16 - Java

The same exception was thrown if a DB table had an old unremoved column.

For example: attribute_id NOT NULL BIGINT(20), and attributeId NOT NULL BIGINT(20),

After removing the not used attribute, in my case contractId, the problem was resolved.

Solution 17 - Java

I had this issue, by mistake I had placed @Transient annotation above that particular attribute. In my case this error make sense.

Solution 18 - Java

This happened to me with a @ManyToMany relationship. I had annotated one of the fields in the relationship with @JoinTable, I removed that and used the mappedBy attribute on @ManyToMany instead.

Solution 19 - Java

I tried the code and in my case the code below solve the issue. I had not settled the schema properly

@Entity
    @Table(name="table"
         ,catalog="databasename"
      )

Please try to add ,catalog="databasename" the same as I did.

,catalog="databasename"

Solution 20 - Java

In my case, I altered that offending tables and the field "id" in question I made it AUTO_INCREMENT, I still need to figure out why on deployment time it was not making it "AUTO_INCREMENT" so that I have to do it by myself!

Solution 21 - Java

What about this:

<set name="fieldName" cascade="all"> 
   <key column="id" not-null="true" />
   <one-to-many class="com.yourClass"/>
</set>

I hope it helps you.

Solution 22 - Java

Try to change Long object type to long primitive type (if using primitives is ok for you).

I had the same problem and changing type helped me.

Solution 23 - Java

"Field 'id' doesn't have a default value" because you didn't declare GenerationType.IDENTITY in GeneratedValue Annotation.

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;

Solution 24 - Java

This issue is because sometimes you need to again update/create the database or sometimes if you have added the field in db table but not not entity class then it can not insert any null value or zero so this error came. So check both side.Db and Entity class.

Solution 25 - Java

i have got such error in GCP cloud sql when model field didn't match correct table field in db. Example: when in model field is fieldName
table in db should have field field_name Fixing table field name helped me.

Solution 26 - Java

I solved it changuing @GeneratedValue(strategy = GenerationType.IDENTITY) by @GeneratedValue(strategy = GenerationType.AUTO)

By the way i didn't need to put it to create, just:

spring.jpa.hibernate.ddl-auto: update

Solution 27 - Java

I solved similar problem, when I altered the database column type , and did not add auto_increment. After adding back auto_increment in the alter table command (as in my original table creation) it worked

Solution 28 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndr&#233; ChalellaView Question on Stackoverflow
Solution 1 - JavaAndré ChalellaView Answer on Stackoverflow
Solution 2 - JavaGreg KeyesView Answer on Stackoverflow
Solution 3 - JavaSteve KuoView Answer on Stackoverflow
Solution 4 - Javaanzie001View Answer on Stackoverflow
Solution 5 - JavaSenView Answer on Stackoverflow
Solution 6 - JavaKavitha yadavView Answer on Stackoverflow
Solution 7 - JavaSahan JayasumanaView Answer on Stackoverflow
Solution 8 - JavaDavid PhamView Answer on Stackoverflow
Solution 9 - JavanizeView Answer on Stackoverflow
Solution 10 - Javauser2982704View Answer on Stackoverflow
Solution 11 - JavaSHIVAView Answer on Stackoverflow
Solution 12 - JavaAhmad MerghanyView Answer on Stackoverflow
Solution 13 - JavaalaptikoView Answer on Stackoverflow
Solution 14 - JavaArunView Answer on Stackoverflow
Solution 15 - JavaEricView Answer on Stackoverflow
Solution 16 - JavaViktor ReinokView Answer on Stackoverflow
Solution 17 - Javauser158View Answer on Stackoverflow
Solution 18 - Javagary69View Answer on Stackoverflow
Solution 19 - JavaJusto MiguelView Answer on Stackoverflow
Solution 20 - JavaIshimwe Aubain ConsolateurView Answer on Stackoverflow
Solution 21 - JavaDavid DavilaView Answer on Stackoverflow
Solution 22 - JavaOlgaView Answer on Stackoverflow
Solution 23 - JavaDracula OppaView Answer on Stackoverflow
Solution 24 - JavaShubhamView Answer on Stackoverflow
Solution 25 - Javajhenya-dView Answer on Stackoverflow
Solution 26 - JavaVikcenView Answer on Stackoverflow
Solution 27 - JavaKris SwatView Answer on Stackoverflow
Solution 28 - JavatarhackView Answer on Stackoverflow