I have a j2ee application using hibernate with annotation. How do I annotate the Id field in my pojo class to set it as auto increment or auto generated. and in adding the bean do I leave that field in my bean null?
I have a j2ee application using hibernate with annotation. How do I annotate the Id field in my pojo class to set it as auto increment or auto generated. and in adding the bean do I leave that field in my bean null?
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
and you leave it null (0) when persisting. (null if you use the Integer / Long wrappers)
In some cases the AUTO strategy is resolved to SEQUENCE rathen than to IDENTITY or TABLE, so you might want to manually set it to IDENTITY or TABLE (depending on the underlying database).
It seems SEQUENCE + specifying the sequence name worked for you.
If you have a numeric column that you want to auto-increment, it might be an option to set columnDefinition directly. This has the advantage, that the schema auto-generates the value even if it is used without hibernate. This might make your code db-specific though:
import javax.persistence.Column;
@Column(columnDefinition = "serial") // postgresql
In case anyone "bumps" in this SO question in search for strategies for Informix table when PK is type Serial.
I have found that this works...as an example.
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "special_serial_pk")
private Integer special_serial_pk;
For this to work make sure when you do session.SaveOrUpdate you pass the value for the column special_serial_pk NULL .
In my case i do an HTML POST with JSON like so...
{
"special_serial_pk": null, //<-- Field to be incremented
"specialcolumn1": 1,
"specialcolumn2": "I love to code",
"specialcolumn3": true
}
Using netbeans New Entity Classes from Database with a mysql auto_increment column, creates you an attribute with the following hibernate.hbm.xml: id is auto increment