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”
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.
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)“.
Then one popup will appear, click on “Next”.
Select the pojo folder and give name “Users.hbm.xml” and click on finish.
Now, either you can configure the settings from the UI like below snap:
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.
Enter detail like below screen and click on finish button.
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”.
Now select the Exporters tab and select “Use Java 5 Syntax”.
In refresh tab, select “The Project containing the selected resource“.
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
Leave a Reply