Adding Autoincrement Field using <generator/> in Hibernate

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);
....
...
About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 182 other followers

%d bloggers like this: