Step By Step Hibernate Tutorial Using eclipse WTP

Hibernate is the ORM tool widely used in java community to persist the java object using Object Relational Mapping (ORM) concept. ORM reduces number of lines to interact with database with optimized query language which is Hibernate Query language (HQL).

In this example, we will create a simple login application using hibernate tool of eclipse. We will use eclipse WTP (Web Tools Platform), to install “Hibernate Tools”. Follow below steps :

In Eclipse IDE, menu bar, select “Help” >> “Install New Software …” put the Eclipse update site URL “http://download.jboss.org/jbosstools/updates/stable/helios”

Eclipse Install New Software - Hibernate
Eclipse Install New Software – Hibernate

Select the tool and click on “Next”. Do not select all the tools; it will install all the unnecessary tools. We just need hibernate tools.

After installation, restart the eclipse.

If you don’t have the internet connection and want the offline method to add hibernate tools in eclipse. To install the Hibernate Tools, extract the HibernateTools-3.X.zip file and move all the files inside the features folder into the features folder of the eclipse installation directory and move all the files inside the plugins folder into the plugins folder of the ecilpse installation directory.

After restart, Go to Window | Open Perspective | Other, the following dialog box appears, select Hibernate and click the Ok button.

Eclipse Hibernate Perspective
Eclipse Hibernate Perspective

Now let’s see how to define the object/relational mapping using the XML document. This document has .hbm.xml extension. We will now create the mapping between table and object of entity “user” which hold the data from database. So create the package "in.shivasoft.pojo" in src folder.
Right click on project folder and select “Hibernate XML Mapping file (hbm.xml)“.

Hibernate XML Mapping file Menu in Hibernate Tools of Eclipse
Hibernate XML Mapping file Menu in Hibernate Tools of Eclipse

Then one popup will appear, click on “Next”.

Create Hibernate XML Mapping file(s)
Create Hibernate XML Mapping file(s)

Select the pojo folder and give name “Users.hbm.xml” and click on finish.

New Hibernate XML Mapping files (hbm.xml)
New Hibernate XML Mapping files (hbm.xml)

Now, either you can configure the settings from the UI like below snap:

Hibernate 3.0 XML Editor
Hibernate 3.0 XML Editor

Or, write below code :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
 <class entity-name="Users" name="in.shivasoft.pojo.Users" table="Users">
  <meta attribute="description">This class is used to save the info about users</meta>
  <id column="UserId" name="UserId" type="long"/>
  <property column="FName" name="FName" type="string"/>
  <property column="LName"  name="LName" type="string"/>
  <property column="UserTypeId" name="UserTypeId" type="long"/>
  <property column="UserName" name="UserName" type="string"/>
  <property column="Email" name="Email" type="string"/>
  <property column="Pwd" name="Pwd" type="string"/>
  <property column="Note" name="Note" type="string"/>
  <property column="IsActive" name="IsActive" type="boolean"/>
 </class>
</hibernate-mapping>

Now right click and select “hibernate configuration file”. One window will open, there select the “src” folder and click on next.

Hibernate Configuration File (cfg.xml)
Hibernate Configuration File (cfg.xml)

Enter detail like below screen and click on finish button.

Hibernate Configuration File (cfg.xml) Wizard
Hibernate Configuration File (cfg.xml) Wizard

After this add the Users.hbm.xml file to the newly generated xml configuration.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
		"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
		"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class"> org.gjt.mm.mysql.Driver </property>
        <property name="hibernate.connection.password"> root </property>
        <property name="hibernate.connection.url"> jdbc:mysql://localhost/test </property>
        <property name="hibernate.connection.username"> root </property>
        <property name="hibernate.dialect"> org.hibernate.dialect.MySQL5InnoDBDialect </property>
        <mapping resource="in/shivasoft/pojo/Users.hbm.xml"/>
    </session-factory>
</hibernate-configuration>

After the entire configuration, in the toolbar you can select “hibernate code generation tool”.

Hibernate Code Generation Configurations
Hibernate Code Generation Configurations
Hibernate Code Generation Wizard in Eclipse
Hibernate Code Generation Wizard in Eclipse

Now select the Exporters tab and select “Use Java 5 Syntax”.

Hibernate Code Generation Wizard in Eclipse-Exporters Tab
Hibernate Code Generation Wizard in Eclipse-Exporters Tab

In refresh tab, select “The Project containing the selected resource“.

Hibernate Code Generation Wizard in Eclipse- Refresh Tab
Hibernate Code Generation Wizard in Eclipse- Refresh Tab

Now click the run button to finish java code generation. Following code will be generated:

package in.shivasoft.pojo;

// Generated Aug 1, 2011 7:02:59 PM by Hibernate Tools 3.4.0.CR1

/**
 * Users generated by hbm2java
 */
public class Users implements java.io.Serializable {

	private long UserId;
	private String FName;
	private String LName;
	private long UserTypeId;
	private String UserName;
	private String Email;
	private String Pwd;
	private String Note;
	private boolean IsActive;

	public Users() {
	}

	public Users(long UserId) {
		this.UserId = UserId;
	}

	public Users(long UserId, String FName, String LName, long UserTypeId,
			String UserName, String Email, String Pwd, String Note,
			boolean IsActive) {
		this.UserId = UserId;
		this.FName = FName;
		this.LName = LName;
		this.UserTypeId = UserTypeId;
		this.UserName = UserName;
		this.Email = Email;
		this.Pwd = Pwd;
		this.Note = Note;
		this.IsActive = IsActive;
	}

	public long getUserId() {
		return this.UserId;
	}

	public void setUserId(long UserId) {
		this.UserId = UserId;
	}

	public String getFName() {
		return this.FName;
	}

	public void setFName(String FName) {
		this.FName = FName;
	}

	public String getLName() {
		return this.LName;
	}

	public void setLName(String LName) {
		this.LName = LName;
	}

	public long getUserTypeId() {
		return this.UserTypeId;
	}

	public void setUserTypeId(long UserTypeId) {
		this.UserTypeId = UserTypeId;
	}

	public String getUserName() {
		return this.UserName;
	}

	public void setUserName(String UserName) {
		this.UserName = UserName;
	}

	public String getEmail() {
		return this.Email;
	}

	public void setEmail(String Email) {
		this.Email = Email;
	}

	public String getPwd() {
		return this.Pwd;
	}

	public void setPwd(String Pwd) {
		this.Pwd = Pwd;
	}

	public String getNote() {
		return this.Note;
	}

	public void setNote(String Note) {
		this.Note = Note;
	}

	public boolean isIsActive() {
		return this.IsActive;
	}

	public void setIsActive(boolean IsActive) {
		this.IsActive = IsActive;
	}

}

Now create the

HibernateUtil

class. The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. The SessionFactory is threadsafe, so it is not necessary to obtain one for each thread. Here the static singleton pattern is used to instantiate the SessionFactory. The implementation of the HibernateUtil class is shown below.

package in.shivasoft.util;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class HibernateUtil {

	private static final SessionFactory sessionFactory;

	static {

		try {

			sessionFactory = new Configuration().configure()
			.buildSessionFactory();

		} catch (Throwable ex) {

			System.err.println("Initial SessionFactory creation failed." + ex);

			throw new ExceptionInInitializerError(ex);

		}

	}

	public static SessionFactory getSessionFactory() {

		return sessionFactory;

	}
}

Now, create the test application having main method which will demonstrate that how data is saved:

package in.shivasoft.test;

import in.shivasoft.pojo.Users;
import in.shivasoft.util.HibernateUtil;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class TestMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TestMain obj = new TestMain();
		//obj.saveRecord();
		obj.updateUser(12);
		obj.deleteUser(13);
		obj.getList();
	}

	public void saveRecord()
	{
		Users u = new Users(0, "Jitendra", "Zaa", 1, "jitendra.zaa", "jitendra.zaa@JitendraZaa.com", "test", "this is note", true);
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
			session.save(u);
			transaction.commit();
			System.out.println("Data Saved");
		}catch(Exception e)
		{
			e.printStackTrace();
		}finally{session.close();}

	}
	public void deleteUser(long UserId)
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
			Users u = (Users)session.get(Users.class,UserId);
			session.delete(u);
			transaction.commit();
			System.out.println("Data Deleted");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally{
			session.close();
		}
	}
	public void updateUser(long UserId)
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
			Users u = (Users)session.get(Users.class,UserId);
			u.setFName("ShivaSoft");
			transaction.commit();
			System.out.println("Data Updated");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally{
			session.close();
		}
	}

	public void getList()
	{
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction transaction = null;
		try
		{
			transaction = session.beginTransaction();
			List<Users> uList = session.createQuery("from Users").list();
			for(Users u : uList)
			{
				System.out.println("First Name - "+u.getFName());
			}
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally{
			session.close();
		}
	}
}

Needed jar files :

antlr-2.7.6.jar
commons-collections-3.1.jar
dom4j-1.6.1.jar
hibernate-core.3.3.1.GA.jar
javassist-3.9.0.GA.jar
jta-1.1.jar
mysql-connector-java-5.1.1.17-bin.jar
slf4j-api-1.6.1.jar
slf4j-api-1.6.1-tests.jar
slf4j-slf4j-simple-2.0.jar

Posted

in

,

by

Tags:


Related Posts

Comments

31 responses to “Step By Step Hibernate Tutorial Using eclipse WTP”

  1. Jayant Avatar

    nice article, well formatted
    Thanks for sharing

    1. Jitendra Zaa Avatar

      Thanks Jayant.

  2. Rapeepan Suwannakorn Avatar
    Rapeepan Suwannakorn

    very useful article
    thank you for your kindness ^__^

    1. Jitendra Zaa Avatar

      Thanks Rapeepan for reading and comment.

      Regards,
      Jitendra Zaa

  3. Akriti Dubey Avatar
    Akriti Dubey

    Thanks for sharing this useful article.

  4. Gaurav Avatar
    Gaurav

    I m getting [Main]: Console configuration must be specified as an error n its drop down list ie. Main tab parallel to Exporters has no option in Console Configuration drop down list pls help…

    1. Jitendra Zaa Avatar

      Hey Gaurav,
      can you please explain in detail that when u get error and on which line.. or console log of the error so that i can help you.

      Regards,
      Jitendra Zaa

  5. Paras Avatar
    Paras

    Hi Jitendra one question out of context actually…..i m trying to store a mobile number as 9999829215 bt it is stored as 1409894623 can u help…?

    1. Jitendra Zaa Avatar

      Hi Paras,
      Check the data type in java you are using.
      It may be out of range and there fore shift its value on scale.
      Try to make them as a number datatype in mysql and String in java. It will work perfectly.

      Regards,
      Jitendra Zaa

  6. Paras Avatar
    Paras

    I tried String as Mobile_no in my bean and it worked well..thanks Jitendra

  7. babar Avatar
    babar

    nice article. I have one inquiry, you mentioned at the end of the article ‘Needed jar files’. Are these jars needed to be added explicitly even after the installation of Hibernate Tools ?

  8. Kaushal Mishra Avatar
    Kaushal Mishra

    @Gaurav

    you need to create hibernate console configuration file
    just go to file ->new -> hibernate console configuration and then follow the steps.
    and when running the code generation u will get list

  9. vjosh Avatar
    vjosh

    Can you please give us instruction or demo for reverse engineering for eclipse and hibernate platform.

    and also tell me which approach is good reverse engineering or any other..

    Looking forward for your reply ………

  10. vjosh Avatar
    vjosh

    just adding to the last request can we create entire jsf page from the generated hibernate code in eclipse?

  11. Gaurav Avatar
    Gaurav

    @Kaushal Mishra

    Thanks Kaushal for posting about console configuration file.

    Yes,You were right,actually there is no console configuration file for Hibernate….hope you see this post of mine.Now i was again trying this example it asks for a property file when we chooose New->Hibernate Console Configuration File.so at this point what are we supposed to mention for the property file…i mean an existing file is to be choosen or create new file.if we create or use existing….wat actually this property file meant for…?
    and in this case( Example above ) how to use that.
    Thanks in advance.

    1. Jitendra Zaa Avatar

      Hi Gaurav,
      Create New Hibernate File

  12. Nehajindal31 Avatar
    Nehajindal31

    import org.apache.struts.action.ActionServlet;

    this class is imported by which jar file?

    1.  Avatar
      Anonymous

      It Needs “Struts” jar file.
      Regards,
      Jitendra Zaa

  13. Arun Avatar
    Arun

    My mob no: +917204651195

  14. Harry Avatar
    Harry

    Hi Jitendra..great article and helped me a lot..i’ve implemented all the steps and rite now in testing the with main method..when i run the main method i am getting an exception

    Failed to instantiate SLF4J LoggerFactory
    Reported exception:
    java.lang.NoClassDefFoundError: org.slf4j.impl.StaticLoggerBinder

    I have all the jars in the buildpath as per the article wat could be error ?? pls advise

  15. preeti Avatar
    preeti

    hav some problem with code generation

  16. Siddharth Ubale Avatar
    Siddharth Ubale

    I am getting error while “hibernate code generation configuration” error is “Problem while loading mysql driverclass(com.mysql.jdbc.Driver)”

    1. asad Avatar
      asad

      try to test your MySQL DB connection from Dtabase Perspective. and then put the right information in your Hibernate configuration

  17. Joy Avatar
    Joy

    Does not work for me.

    1. JitendraZaa Avatar
      JitendraZaa

      What error you are getting ?

  18. amish Avatar
    amish

    i am getting org.hibernate.InvalidMappingException: could not parse mapping document from resource com/xyz/abc/Student.hbm.xml

  19. ali Avatar
    ali

    I have done everything step by stepy but I have this error when i run this code..
    “Not binding factory to JNDI, no JNDI name configured

    org.hibernate.MappingException: Unknown entity: in.shivasoft.pojo.Users

    at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:580)

    at org.hibernate.impl.SessionImpl.getEntityPersister(SessionImpl.java:1365)

    at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:121)

    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)

    at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)

    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)

    at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)

    at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)

    at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:562)

    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:550)

    at org.hibernate.impl.SessionImpl.save(SessionImpl.java:546)

    at in.shivasoft.test.TestMain.saveRecord(TestMain.java:33)

    at in.shivasoft.test.TestMain.main(TestMain.java:19)

    1. ali Avatar
      ali

      Solved it after removing ‘entity-name’ attribute in user.hbm.xml. it will work fine. it should be

  20. Richard Garces Riffo Avatar
    Richard Garces Riffo

    Me funcionó perfectamente, gracias.

  21. Dipesh Avatar
    Dipesh

    Amazing!!
    Thank you.

  22. Shaik Rizwan Avatar
    Shaik Rizwan

    Thanks for sharing the alternative of Help –> Eclipse Marketplace…, It help’s me.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Jitendra Zaa

Subscribe now to keep reading and get access to the full archive.

Continue Reading