Adding Autoincrement Field using <generator/> in Hibernate
July 2, 2011 Leave a comment
In my previous post, We are adding id of the user by using parameter value to the constructor. In general jsp, servlet code If id field is required to be auto increment, we will select the maximum value of the field and next value will be inserted into the field. Same operation is done by using “incremental” class property of <generator> in Hibernate.
If we need to implement this funtionality to the previous example. We have to just remove id parameter from the constructor and edit the user id mapping to <generator/>. Changes has been highlighted in below piece of code.
User.java
...
...
public User(String u_name, String u_password)
{
this.u_name=u_name;
this.u_password=u_password;
}
...
...
User.hbm.xml
... ... <id name="u_id" type="integer" column="id"> <generator class="increment"/> </id> ... ...
Example.java
...
...
session=sessionFactory.openSession();
User user=new User("Sharma","newpassword");
session.save(user);
....
...


Recent Comments