Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML

Search:
   Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML Facing Programming Problem? Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Hibernate
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments
Using Hibernate to generate id incrementally
As we have seen in the last section that the increment class generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table.
 
 

Using Hibernate <generator> to generate id incrementally

                         

As we have seen in the last section that the increment class generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. In this lesson I will show you how to write running program to demonstrate it. You should not use this method to generate the primary key in case of clustured environment.

In this we will create a new table in database, add mappings in the contact.hbm.xml file, develop the POJO class (Book.java), write the program to test it out.

Create Table in the mysql database:
User the following sql statement to create a new table in the database.
 CREATE TABLE `book` ( 
`id` int(11) NOT NULL default '0', 
`bookname` varchar(50) default NULL, 
PRIMARY KEY (`id`) 
) TYPE=MyISAM

Developing POJO Class (Book.java)
Book.java is our POJO class which is to be persisted to the database table "book".
/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Java Class to map to the database Book table
 */
package roseindia.tutorial.hibernate;


public class Book {
  private long lngBookId;
  private String strBookName;
  
  /**
   @return Returns the lngBookId.
   */
  public long getLngBookId() {
    return lngBookId;
  }
  /**
   @param lngBookId The lngBookId to set.
   */
  public void setLngBookId(long lngBookId) {
    this.lngBookId = lngBookId;
  }
  /**
   @return Returns the strBookName.
   */
  public String getStrBookName() {
    return strBookName;
  }
  /**
   @param strBookName The strBookName to set.
   */
  public void setStrBookName(String strBookName) {
    this.strBookName = strBookName;
  }
}

Adding Mapping entries to contact.hbm.xml
Add the following mapping code into the contact.hbm.xml file

<class name="roseindia.tutorial.hibernate.Book" table="book">
     <id name="lngBookId" type="long" column="id" >
        <generator class="increment"/>
     </id>

    <property name="strBookName">
         <column name="bookname" />
     </property>
</class>

 Note that we have used increment for the generator class. *After adding the entries to the xml file copy it to the bin directory of your hibernate eclipse project(this step is required if you are using eclipse).

Write the client program and test it out
Here is the code of our client program to test the application.

/**
 @author Deepak Kumar
 *
 * http://www.roseindia.net
 * Example to show the increment 
class of hibernate 
generator element to 
 * automatically generate 
the primay key

 */
package roseindia.tutorial.hibernate;

//Hibernate Imports
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class IdIncrementExample {
  public static void main
(
String[] args) {
    Session session = null;

    try{
      // This step will read 
hibernate.cfg.xml and 
prepare hibernate for use

      SessionFactory sessionFactory = 
new Configuration().configure()
.buildSessionFactory
();
  session =sessionFactory.openSession();
       
      org.hibernate.Transaction tx = 
session.beginTransaction
();
       
      //Create new instance 
of Contact and set values in
 it by reading them from form object

       System.out.println("
Inserting Book object 
into database.."
);
      Book book = new Book();
      book.setStrBookName("Hibernate 
Tutorial"
);
      session.save(book);
      System.out.println("Book object 
persisted to the database."
);
          tx.commit();
          session.flush();
          session.close();
    }catch(Exception e){
      System.out.println(e.getMessage());
    }finally{
      }
    
  }
}

To test the program Select Run->Run As -> Java Application from the eclipse menu bar. This will create a new record into the book table.

 

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

22 comments so far (
post your own) View All Comments Latest 10 Comments:

I am getting next:

Database(): group="null"
props="null"
Database(): group="null"
props="null"
Database(): group="null"
props="null"
Cannot open connection

And so in each example... can any one help me in this?

Posted by bandr on Tuesday, 08.5.08 @ 03:20am | #70994

Caused by: java.sql.BatchUpdateException: Duplicate key or integrity constraint violation message from server: "Duplicate entry '4' for key 1"
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1540)
at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:294)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:58)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:195)
... 44 more

Posted by nikunj on Wednesday, 05.14.08 @ 14:04pm | #59783

org.hibernate.MappingException: Error reading resource: contact.hbm.xml

Posted by ghouse on Thursday, 04.24.08 @ 22:56pm | #57813

As a novice,After a long google search for Hibernate documents, I have found this site. This is very useful.I Wholeheartedly thank roseindia.net for their valuable help. Beginners will definitely find this site pretty useful.

Posted by Karthik on Wednesday, 01.9.08 @ 15:37pm | #44847

this site is very usefull but i am sufferring some problem my hibernate prog for storing the data works fine but data is not store in that
and on cosole this is o/p i also create trasaction object and commit.
log4j:WARN No appenders could be found for logger (org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Hibernate: select max(objectid) from dtproperties
Hibernate: insert into dtproperties (property, value, version, objectid) values (?, ?, ?, ?)
Data inserted into database

Posted by rajesh Bobe on Tuesday, 01.1.08 @ 14:31pm | #44317

I am getting the below error while executing second example book
"could not fetch initial value for increment generator"
need solutions..

Posted by srinivas on Wednesday, 12.12.07 @ 13:00pm | #41923

WARNING: No configuration found. Configuring ehcache from ehcache-failsafe.xml found in the classpath: jar:file:/C:/test/hibernate/lib/ehcache-1.1.jar!/ehcache-failsafe.xml
Exception in thread "main" java.lang.NullPointerException at oseindia.tutorial.hibernate.FirstExample.main(FirstExample.java:36)

Posted by bayaaaaa on Friday, 12.7.07 @ 06:29am | #41491

I am executing the first example, I am getting an exception...
org.hibernate.InvalidMappingException: Could not parse mapping document from resource contact.hbm.xml

Help me out in solving this problem.

Posted by Rupa on Thursday, 10.4.07 @ 15:38pm | #31364

@ brijesh Kachalia & kanchan : I may not be an expert on this, but my guess is that your contact.hbm.xml is not placed in the correct directory...

Posted by Andrew on Wednesday, 03.28.07 @ 06:22am | #12817

hi,
i hav developed a hibernate program & found an error----------Error reading resource: contact.hbm.xml.
can any one help me in this???????

Posted by kanchan on Tuesday, 03.20.07 @ 11:35am | #12244

Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.