Hibernate–Java Environment setup

Environment

  1. Eclipse 3.7 Indigo IDE Download
  2. Hibernate 4.1.1 Download
  3. JavaSE 1.6  Download
  4. MySQL 5.1 Download
  5. JDBC Driver for MySQL ((MySQL-connector-java-5.1.19.zip)) Download
  6. Extract the Hibernate, MySql driver files in a separate folder

 

Step 1:

  1. 1. In the eclipse, Click New –>  Java Project
  2. Enter the Project Name <ExampleXXXX>
  3. Click Next
  4. Goto Libraries Tab as shown

         image 

Click On Add External Jar files. Add the following files from the hibernate folder and MySQL driver folder.

  • antlr-2.7.7.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.1.Final.jar
  • hibernate-core-4.1.1.Final.jar
  • hibernate-entitymanager-4.1.1.Final.jar
  • hibernate-jpa-2.0-api-1.0.1.Final.jar
  • javassist-3.15.0-GA.jar
  • jboss-logging-3.1.0.GA.jar
  • jboss-transaction-api_1.1_spec-1.0.0.Final.jar
  • mysql-connector-java-5.1.18-bin.jar

image

Click Finish Button

 

Step 2:

Now let us setup the mysql. Create the following table in mysql

image

Insert some values as shown here

image

Step 3:

Now let us create the Patient Java Bean class with JPA Annotations

 

           image

  1. Right Click on Src folder as shown
  2. Select New->Class
  3. Enter package name as mypack and Class name as patient
  4. Here is the Java Bean code
package mypack;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Column;



@Entity
@Table(name="patient")
public class patient {

private Integer id;
private String firstName;
private String lastName;

@Id
@GeneratedValue
@Column(name="ID")
public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

@Column(name="firstname")
public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

@Column(name="lastname")
public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

}


Step 4:



Create hibernate.cfg.xml




    1. Right Click on Src folder
    2. Select New –> Other->General->File
    3. Enter the file name as hibernate.cfg.xml
    4. Goto the Source view and paste the following code
    5. image


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/sampledb</property>
<property name="connection.username">root</property>
<property name="connection.password">123</property>

<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>

<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>

<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>

<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>

<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>

<!-- Mapping Classes -->
<mapping class="mypack.patient" />

</session-factory>
</hibernate-configuration>


Step 5:



Create Test.java to test all the above are fine.



  1. Right Click on Src->mypack folder
  2. Select New –> Class
  3. Enter the Class Name as Test


image


Test.Java code


package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;

public class Test {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
getAllRecords();
}

public static void getAllRecords() {

try {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
factory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
System.out.println("**Example : Hibernate SessionFactory**");
System.out.println("----------------------------------------");

List allpatients;

Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q1 = session.createQuery("from patient");
allpatients = q1.list();
for (int i = 0; i < allpatients.size(); i++) {
patient pt = (patient) allpatients.get(i);
System.out.println(pt.getLastName());
}
tx.commit();
} catch (HibernateException e) {
if (tx != null)
tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}

}


Step 6:


Right click on Test.Java in the Editor window and Select Run as –> Java Application


The output as follows


**Example : Hibernate  SessionFactory**
----------------------------------------
Hibernate: select patient0_.ID as ID0_, patient0_.firstname as firstname0_, patient0_.lastname as lastname0_ from patient patient0_
John
DAVID
JOSEPH


 


 


Step 7:



Now we will move all the hibernate session creation part into separate class and we will reuse whenever we need it.  We will call this as Hibernate Utility class


package Utility;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

public class HibernateUtil {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static Configuration getInitConfiguration() {
Configuration config = new Configuration();
config.configure();
return config;
}

public static Session getSession() {
if (factory == null) {
Configuration config = HibernateUtil.getInitConfiguration();
serviceRegistry = new ServiceRegistryBuilder().applySettings(
config.getProperties()).buildServiceRegistry();
factory = config.buildSessionFactory(serviceRegistry);
}
Session hibernateSession = factory.getCurrentSession();
return hibernateSession;
}

public static Session beginTransaction() {
Session hibernateSession;
hibernateSession = HibernateUtil.getSession();
hibernateSession.beginTransaction();
return hibernateSession;
}

public static void CommitTransaction() {
HibernateUtil.getSession().getTransaction().commit();
}

public static void closeSession() {
HibernateUtil.getSession().close();
}

public static void rollbackTransaction() {
HibernateUtil.getSession().getTransaction().rollback();
}

}


 


Step 8:


Now let us reduce the code in test.java as shown


package mypack;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.HibernateException;

import Utility.HibernateUtil;

public class Test {

private static SessionFactory factory;
private static ServiceRegistry serviceRegistry;

public static void main(String[] args) {
getAllRecords();
}

public static void getAllRecords() {
List allpatients;
Session session = HibernateUtil.beginTransaction();
Query q1 = session.createQuery("from patient");
allpatients = q1.list();
for (int i = 0; i < allpatients.size(); i++) {
patient pt = (patient) allpatients.get(i);
System.out.println(pt.getLastName());
}
HibernateUtil.CommitTransaction();
}

}