Saturday 5 April 2014

Cannot insert the value NULL into column 'stateNo', table 'S3H4.dbo.State'; column does not allow nulls. INSERT fails.

I got the following error when trying to persist the State entity using the code - session.persist(state);

Apr 05, 2014 2:25:50 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Cannot insert the value NULL into column 'stateNo', table 'S3H4.dbo.State'; column does not allow nulls. INSERT fails.

I was auto-generating the primary key using the GeneratedValue annotations given below.
@Entity
@Table(name="STATE")
public class State {

@Id
@GeneratedValue
private int stateNo;
 //other properties and their getters and setters.
}

This strategy of auto-generating primary keys worked fine as long as I was using Oracle 11g. As soon as I moved to SQL Server 2008 R2. I got the error message mentioned in red above.

Solution
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.GenericGenerator;
@Entity
@Table(name="STATE")
public class State {

@Id
@GeneratedValue(generator="stateNoGenerator")
@GenericGenerator(strategy="increment",name="stateNoGenerator")
@Column(name="STATENO",length=10)
private int stateNo;
//other properties and their getters and setters.
}

Adding the GenericGenerator annotation did the trick. Do  note that GenericGenerator is present within org.hibernate.annotations package and not within  javax.persistence package as one would normally expect.
Add the generator attribute in the GeneratedValue annotation specifying the name of the GenericGenerator.

No comments:

Post a Comment