Hibernate Auto Increment ID
Do it as follows :-
@Id
@GenericGenerator(name="kaugen" , strategy="increment")
@GeneratedValue(generator="kaugen")
@Column(name="proj_id")
public Integer getId() {
return id;
}
You can use any arbitrary name instead of kaugen. It worked well, I could see below queries on console
Hibernate: select max(proj_id) from javaproj
Hibernate: insert into javaproj (AUTH_email, AUTH_firstName, AUTH_lastName, projname, proj_id) values (?, ?, ?, ?, ?)
FYI
Using netbeans New Entity Classes from Database with a mysql *auto_increment* column, creates you an attribute with the following annotations:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
@NotNull
private Integer id;
This was getting me the same an error saying the column must not be null, so i simply removed the @NotNull anotation leaving the attribute null, and it works!
Hibernate defines five types of identifier generation strategies:
AUTO - either identity column, sequence or table depending on the underlying DB
TABLE - table holding the id
IDENTITY - identity column
SEQUENCE - sequence
identity copy – the identity is copied from another entity
Example using Table
@Id
@GeneratedValue(strategy=GenerationType.TABLE , generator="employee_generator")
@TableGenerator(name="employee_generator",
table="pk_table",
pkColumnName="name",
valueColumnName="value",
allocationSize=100)
@Column(name="employee_id")
private Long employeeId;
for more details, check the link.
@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.