Wednesday, November 4, 2009

How to persist the java objects using Hibernate ORM framework?

The answer to this question takes the form of a tutorial, where I will go in details, step by step. Hibernate reduces number of lines of coding/writing SQLs for persisting object into the database considerably. This takes focus from doing repetitive work to focus on implementing business logic to address a business problem.

Hibernate uses a object relation mapping file in form of an XML or properties file. In this file there exists a mapping between a Java object and corresponding database table.First thing first, let us create the needed environment to achieve our objective.

We need following tools and binaries:

1.The IDE used is Eclipse Galileo(latest one while writing this post).
2.Hibernate binaries(Hibernate Core 3.3.2 GA and Hibernate Tools 3.2.4 GA)can be downloaded from here
3.Database HSQLDB 1.9

The next step is unzip Hibernate Tools 3.2.4 GA and put features and plugins contents to features and plugins directory of Eclipse Galileo. Ensure you have closed Eclipse IDE prior to this step and once you are done with copying part then restart the Eclipse Galileo.


You have to ensure following JARs have been included in the project:


-hibernate3.jar(contains all core Hibernate files)
-antlr-2.7.6.jar
-commons-collections-3.1.jar
-dom4j-1.6.1.jar
-javassist-3.9.0.GA.jar
-jta-1.1.jar
-slf4j-api-1.5.8.jar(used for logging purposes)
-slf4j-simple-1.5.8.jar(download it from here)
-hsqldb.jar(used for connecting to HSQL Database)


Once all above steps are over then choose Hibernate perspective in Eclipse IDE.Go to Window-Open Perspective-Other and select Hibernate perspective as show in the image given below:


Next step is to define object relation mapping XML file which has .hbm.xml extension. First create a package named com.iqjava.employee and inside this package we will create a new OR mapping XML named 'employee.hbm.xml'.(Right click on package com.iqjava.employee, select New -Hibernate XML Mapping File)


having contents as given below:
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "https://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.iqjava.employee.Employee" table="EMP"> <meta attribute="class-description"> This class contains the employee details. </meta> <id name="employeeId" type="long" column="EMP_ID"> <generator class="native"/> </id> <property name="employeeName" type="string" column="EMP_NAME" not-null="true" /> </class> </hibernate-mapping>


In this OR Mapping file, class element depicts the class which will be mapped with an underlying table of RDBMS, in this case EMP table.The id element represents primary key of the table wherein attribute name represents a variable(employeeId) in Java class which is mapped with the column (attribute of id element) of the table(EMP_ID).

The type attribute represents the hibernate mapping type which will convert data from Java String type to underlying database String datatype .The generator element is used for automatically generate the primary key values.The native value of class attributes ascertain that hibernate picks either identitysequence or hilo algorithm depending upon the capabilities of the underlying database. The property element is used to link a property in the Java class to a column in the database table.

The next step is to create Hibernate configuration file.Select 'src' folder, right click and choose New--Hibernate Configuration File menu option.


The following wizard window will appear and you will have to enter the data as shown in the picture given below:



The content of the Hibernate configuration file is shown as below:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "https://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="hibernate.connection.url">jdbc:hsqldb:hsql://localhost</property> <property name="hibernate.connection.username">sa</property> <property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property> <property name="connection.password"></property> <property name="connection.pool_size">1</property> <property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">create</property> <mapping resource="com/iqjava/employee/employee.hbm.xml"/> </session-factory> </hibernate-configuration>

Once you are done with this step then next step is to create a new a Hibernate console configuration. To do this right click the project folder, select New --- Hibernate Console Configuration.The following Wizard appears:





By default the wizard will load the Hibernate configuration file information. Just click the Finish button to create the Hibernate console configuration.
Once above step is done, you can generate code by selecting the Hibernate Code Generation Configurations option form Run option on toolbar as depicted below:


Once the Wizard shows up, please ensure following tabs have details according to images shown as below:




Once all these settings are ensured then hit Run button and you get Employee.java file being generated from .hbm.xml file and its contents are as shown below:
package com.iqjava.employee; // Generated Nov 3, 2009 6:02:21 PM by Hibernate Tools 3.2.4.GA /** * This class contains the employee details. */ public class Employee implements java.io.Serializable { private long employeeId; private String employeeName; public Employee() { } public Employee(String employeeName) { this.employeeName = employeeName; } public long getEmployeeId() { return this.employeeId; } public void setEmployeeId(long employeeId) { this.employeeId = employeeId; } public String getEmployeeName() { return this.employeeName; } public void setEmployeeName(String employeeName) { this.employeeName = employeeName; } }
Now we create HibernateUtil.java file which creates a SessionFactory from the Hibernate configuration file. The implementation of HibernateUtil.java is given as below:


package com.iqjava.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; } }

The next step is to create an ExecutionClass.java. The implementation of this class is given as below:

package com.iqjava.employee; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.Transaction; import java.util.List; import java.util.Iterator; import com.iqjava.util.HibernateUtil; public class ExecutionClass { public static void main(String[] args) { ExecutionClass obj = new ExecutionClass(); Long empId1 = obj.saveEmployee("John"); Long empId2 = obj.saveEmployee("Paul"); Long empId3 = obj.saveEmployee("Bill"); obj.listEmployee(); System.out.println("Updating emp3...."); obj.updateEmployee(empId3, "Michael"); System.out.println("Deleting emp2...."); obj.deleteEmployee(empId2); System.out.println("List employees...."); obj.listEmployee(); } public Long saveEmployee(String employeeName) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; Long empId = null; try { transaction = session.beginTransaction(); Employee emp = new Employee(); emp.setEmployeeName(employeeName); empId = (Long) session.save(emp); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } return empId; } public void listEmployee() { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); List emps = session.createQuery("from Employee").list(); for (Iterator iterator = emps.iterator(); iterator.hasNext();) { Employee emp = (Employee) iterator.next(); System.out.println(emp.getEmployeeName()); } transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } public void updateEmployee(Long empId, String employeeName) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Employee emp = (Employee) session.get(Employee.class, empId); emp.setEmployeeName(employeeName); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } public void deleteEmployee(Long empId) { Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = null; try { transaction = session.beginTransaction(); Employee emp = (Employee) session.get(Employee.class, empId); session.delete(emp); transaction.commit(); } catch (HibernateException e) { transaction.rollback(); e.printStackTrace(); } finally { session.close(); } } }

The code details of the above are self explanatory.The project structure in Eclipse is depicted as shown below:

Before executing the ExecutionClass.java., please ensure you have started the HSQLDB server as depicted in image shown below



Once the code in ExecutionClass.java is executed then console of Eclipse IDE shows following output:
31 [main] INFO org.hibernate.cfg.Environment - Hibernate 3.3.2.GA 31 [main] INFO org.hibernate.cfg.Environment - hibernate.properties not found 47 [main] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist 47 [main] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling 219 [main] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml 219 [main] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml 437 [main] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : com/iqjava/employee/employee.hbm.xml 594 [main] INFO org.hibernate.cfg.HbmBinder - Mapping class: com.iqjava.employee.Employee -> EMP 625 [main] INFO org.hibernate.cfg.Configuration - Configured SessionFactory: null 750 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Using Hibernate built-in connection pool (not for production use!) 750 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - Hibernate connection pool size: 1 750 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - autocommit mode: false 781 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - using driver: org.hsqldb.jdbcDriver at URL: jdbc:hsqldb:hsql://localhost 781 [main] INFO org.hibernate.connection.DriverManagerConnectionProvider - connection properties: {user=sa, password=****} 1140 [main] INFO org.hibernate.cfg.SettingsFactory - RDBMS: HSQL Database Engine, version: 1.9.0 1140 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC driver: HSQL Database Engine Driver, version: 1.9.0 1203 [main] INFO org.hibernate.dialect.Dialect - Using dialect: org.hibernate.dialect.HSQLDialect 1219 [main] INFO org.hibernate.transaction.TransactionFactoryFactory - Using default transaction strategy (direct JDBC transactions) 1219 [main] INFO org.hibernate.transaction.TransactionManagerLookupFactory - No TransactionManagerLookup configured (in JTA environment, use of read-write or transactional second-level cache is not recommended) 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic flush during beforeCompletion(): disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Automatic session close at end of transaction: disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch size: 15 1219 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC batch updates for versioned data: disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Scrollable result sets: enabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - JDBC3 getGeneratedKeys(): enabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Connection release mode: auto 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Default batch fetch size: 1 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Generate SQL with comments: disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL updates by primary key: disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Order SQL inserts for batching: disabled 1219 [main] INFO org.hibernate.cfg.SettingsFactory - Query translator: org.hibernate.hql.ast.ASTQueryTranslatorFactory 1234 [main] INFO org.hibernate.hql.ast.ASTQueryTranslatorFactory - Using ASTQueryTranslatorFactory 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Query language substitutions: {} 1234 [main] INFO org.hibernate.cfg.SettingsFactory - JPA-QL strict compliance: disabled 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Second-level cache: enabled 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Query cache: disabled 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Cache region factory : org.hibernate.cache.impl.NoCachingRegionFactory 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Optimize cache for minimal puts: disabled 1234 [main] INFO org.hibernate.cfg.SettingsFactory - Structured second-level cache entries: disabled 1250 [main] INFO org.hibernate.cfg.SettingsFactory - Echoing all SQL to stdout 1250 [main] INFO org.hibernate.cfg.SettingsFactory - Statistics: disabled 1250 [main] INFO org.hibernate.cfg.SettingsFactory - Deleted entity synthetic identifier rollback: disabled 1250 [main] INFO org.hibernate.cfg.SettingsFactory - Default entity-mode: pojo 1250 [main] INFO org.hibernate.cfg.SettingsFactory - Named query checking : enabled 1359 [main] INFO org.hibernate.impl.SessionFactoryImpl - building session factory 1797 [main] INFO org.hibernate.impl.SessionFactoryObjectFactory - Not binding factory to JNDI, no JNDI name configured 1812 [main] INFO org.hibernate.tool.hbm2ddl.SchemaExport - Running hbm2ddl schema export 1812 [main] INFO org.hibernate.tool.hbm2ddl.SchemaExport - exporting generated schema to database 1812 [main] INFO org.hibernate.tool.hbm2ddl.SchemaExport - schema export complete Hibernate: insert into EMP (EMP_ID, EMP_NAME) values (null, ?) Hibernate: insert into EMP (EMP_ID, EMP_NAME) values (null, ?) Hibernate: insert into EMP (EMP_ID, EMP_NAME) values (null, ?) Hibernate: select employee0_.EMP_ID as EMP1_0_, employee0_.EMP_NAME as EMP2_0_ from EMP employee0_ John Paul Bill Updating emp3.... Hibernate: select employee0_.EMP_ID as EMP1_0_0_, employee0_.EMP_NAME as EMP2_0_0_ from EMP employee0_ where employee0_.EMP_ID=? Hibernate: update EMP set EMP_NAME=? where EMP_ID=? Deleting emp2.... Hibernate: select employee0_.EMP_ID as EMP1_0_0_, employee0_.EMP_NAME as EMP2_0_0_ from EMP employee0_ where employee0_.EMP_ID=? Hibernate: delete from EMP where EMP_ID=? List employees.... Hibernate: select employee0_.EMP_ID as EMP1_0_, employee0_.EMP_NAME as EMP2_0_ from EMP employee0_ John Michael

Check if the database schema is created and the data is inserted into the EMP table or not. Simply open a new command prompt, go to the hsqldb installed directory and type the following command.
java -cp ./lib/hsqldb.jar org.hsqldb.util.DatabaseManager
The dialog box as shown below pops up


and here select Type as "HSQL Database Engine Server" and click Ok.You see the HSQL Database Manager window as shown below, type the SQL as shown and press execute button. The result shown depicts data existing in the database.


One can exit from the database by typing 'shutdown' and hitting Execute button.
blog comments powered by Disqus
 

Disclaimer
Interview Questions On Java,Java EE Copyright © 2016. Reads: best tracker