I have created a seam applcation with Hibernate(default) a ORM provider. While persisting an entity, it throws following error:
Caused by: java.sql.SQLException: Field 'COUNTRY_ID' doesn't have a default value
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073)
Its thrown because the Primary key is not generated by Hibernate before persisting entity.
@Entity
@Table(name = "country")
public class Country implements java.io.Serializable {
private Integer countryId;
//other instance variables...
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "COUNTRY_ID", unique = true, nullable = false)
public Integer getCountryId() {
return this.countryId;
}
public void setCountryId(Integer countryId) {
this.countryId = countryId;
}
When I make changes in ‘Country’ Table, i.e make COUNTRY.COUNTRY_ID as AUTO_INCREMENT (MySQL database) then the above code persists Country entity. Even after trying strategy
@GeneratedValue(strategy = GenerationType.IDENTITY)
error occurs if I don’t make COUNTRY_ID as AUTO_INCREMENT.
So, is it necessary that Primary keys should be made Auto Increment in table? Why doesn’t Hibernate create a unique primary key (using HiLo algorithm) before persisting the entity if the primary key is not marked as AUTO_INCREMENT in database table.
Thanks in advance.
Regards
GenerationType.AUTO means that hibernate will select a generation strategy depending on the database capabilities: for MySQL will select the identity strategy. In your case specifying GenerationType.AUTO is the same with GenerationType.IDENTITY.
In turn, GenerationType.IDENTITY requires to have an auto increment on your id column.
You should try other strategies if you want hibernate to assign values to your id column: for example hilo. But letting hibernate assign values for your id columns is recommended only for testing.