Menu

Wednesday, October 19, 2011

Hibernate with Annotations


In this tutorial, Java Annotation is used to simplify the mapping configuration. This program is same as this example except some small change in the Persistence class and the "hibernate.cfg.xml".


Step 1: Download the latest version of the Hibernate from the official site. http://www.hibernate.org/ and extract the distribution to desired folder. 

Step 2:  
This example program requires the below jar files. These files are in the Hibernate distribution that you have downloaded.

       hibernate-distribution-3.6.7.Final\lib\required\antlr-2.7.6.jar
       hibernate-distribution-3.6.7.Final\lib\required\commons-collections-3.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\dom4j-1.6.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\javassist-3.12.0.GA.jar
       hibernate-distribution-3.6.7.Final\lib\required\jta-1.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\slf4j-api-1.6.1.jar

       hibernate-distribution-3.6.7.Final\lib\jpa\hibernate-jpa-2.0-api-1.0.1.Final.jar

       hibernate-distribution-3.6.7.Final\hibernate3.jar

       Download the latest version of the MySQL connector jar file from http://dev.mysql.com/downloads/connector/j/        mysql-connector-java-5.0.5-bin.jar

Step 3: Create a My SQL database to connect from the hibernate.

      CREATE DATABASE test;
      USE test;
      CREATE TABLE employee (
               id  INT NOT NULL AUTO_INCREMENT   PRIMARY KEY,
               first_name VARCHAR(25) NOT NULL,
               last_name VARCHAR(25) NOT NULL
      );

Step 4: Create a java project in Eclipse IDE
  1. File ----> New ----> Java Project
  2. Enter project name and click finish.
  3. Create a lib folder under the project and add required jar files for hibernate.
  4. Now add these jar files in the class path to avoid compilation errors. To do this, right click on the project ----> Properties ----> Java Build Path ----> Add Jar ----> Go to lib folder ----> Select all the jar files.
Step 5:  First create a Persistence class. The mapping between the Persistence class and Table has been done using Java Annotation.

package com.hibernate.example;

package com.hibernate.example;

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

@Entity
@Table (name="EMPLOYEE")
public class Employee {
 
 @Id 
 @Column (name="ID")
 private int id;
 
 @Column (name="FIRST_NAME")
 private String firstName;
 
 @Column (name="LAST_NAME")
 private String lastName; 

 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 } 
}

Step 6:  Create a folder named "config" to keep all the configuration files in one place.

Create xml file "hibernate.cfg.xml" under the config folder.

Add this config folder in the build path. To do this, Right Click on the project ---> Java Build Path ---> Sources Tab ---> Add Folder ---> Select the config folder.

Now the configuration files have been successfully added on the projects build path.




Step 8:  Edit the hibernate.cfg.xml file and add database connectivity details.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">akila</property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- Map the class file -->
  <mapping class="com.hibernate.example" />
 </session-factory>
</hibernate-configuration>

Step 9: Create a class to insert a record into the employee table using hibernate.
package com.hibernate.example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Main {
 public static void main(String[] args) {

  Session session = null;
  try {
   // Open Session
   SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
   session = sessionFactory.openSession();
   // Start Transaction
   Transaction tx = session.beginTransaction();

   System.out.println("Insert");

   Employee employee = new Employee();
   employee.setId(1);
   employee.setFirstName("Akila");
   employee.setLastName("Rajendran");
   
   //Save the session
   session.save(employee);
   tx.commit();

   System.out.println("Done");
  } catch (Exception e) {
   System.out.println(e.getMessage());
  } finally {
   session.flush();
   session.close();
  }
 }
}

Step 10: Run the project and check the database.


You might also like this:
  1. Hibernate simple example

Tuesday, October 18, 2011

Hibernate simple program

Step 1: Download the latest version of the Hibernate from the official site. http://www.hibernate.org/ and extract the distribution to desired folder. 

Step 2: 
This example program requires the below jar files. These files are in the Hibernate distribution that you have downloaded.

       hibernate-distribution-3.6.7.Final\lib\required\antlr-2.7.6.jar
       hibernate-distribution-3.6.7.Final\lib\required\commons-collections-3.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\dom4j-1.6.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\javassist-3.12.0.GA.jar
       hibernate-distribution-3.6.7.Final\lib\required\jta-1.1.jar
       hibernate-distribution-3.6.7.Final\lib\required\slf4j-api-1.6.1.jar

       hibernate-distribution-3.6.7.Final\lib\jpa\hibernate-jpa-2.0-api-1.0.1.Final.jar      
      
       hibernate-distribution-3.6.7.Final\hibernate3.jar
    
       Download the latest version of the MySQL connector jar file from http://dev.mysql.com/downloads/connector/j/        mysql-connector-java-5.0.5-bin.jar

Step 3: Create a My SQL database to connect from the hibernate.

      CREATE DATABASE test;
      USE test;
      CREATE TABLE employee (
               id  INT NOT NULL AUTO_INCREMENT   PRIMARY KEY,
               first_name VARCHAR(25) NOT NULL,
               last_name VARCHAR(25) NOT NULL
      );

Step 4: Create a java project in Eclipse IDE
  1. File ----> New ----> Java Project
  2. Enter project name and click finish.
  3. Create a lib folder under the project and add required jar files for hibernate.
  4. Now add these jar files in the class path to avoid compilation errors. To do this, right click on the project ----> Properties ----> Java Build Path ----> Add Jar ----> Go to lib folder ----> Select all the jar files.
Step 5:  First create a Persistence class.
package com.hibernate.example;

public class Employee { 
 private int id; 
 private String firstName; 
 private String lastName; 

 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 } 
}

Step 6:  Create a folder named as "config" to keep all the configuration files in one place.

Create xml files "employee.hbm.xml" and "hibernate.cfg.xml" under the config folder.

Add this config folder in the build path. To do this, Right Click on the project ---> Java Build Path ---> Sources Tab ---> Add Folder ---> Select the config folder.

Now the configuration files have been successfully added on the projects build path. 


Step 7: Map the Employee Persistence class to the Employee table in hibernate mapping file (employee.hbm.xml).
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
 <class name="com.hibernate.example.Employee" table="Employee">
  <id name="id" type="int" column="id">
   <generator class="increment"></generator>
  </id>

  <property name="firstName">
   <column name="first_name" />
  </property>
  <property name="lastName">
   <column name="last_name" />
  </property>
 </class>
</hibernate-mapping>

Step 8:  Create hibernate configuration file where we have to enter all the necessary information to connect to the data base. The configuration file should be named as "hibernate.cfg.xml".
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
 <session-factory>
  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password">akila</property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- Mapping files -->
  <mapping resource="employee.hbm.xml" />
 </session-factory>
</hibernate-configuration>

Step 9: Create a class to insert a record into the employee table using hibernate.
package com.hibernate.example;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class Main {
 public static void main(String[] args) {

  Session session = null;
  try {
   // Open Session
   SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
   session = sessionFactory.openSession();
   // Start Transaction
   Transaction tx = session.beginTransaction();

   System.out.println("Insert");

   Employee employee = new Employee();
   employee.setId(1);
   employee.setFirstName("Akila");
   employee.setLastName("Rajendran");
   
   //Save the session
   session.save(employee);
   tx.commit();

   System.out.println("Done");
  } catch (Exception e) {
   System.out.println(e.getMessage());
  } finally {
   session.flush();
   session.close();
  }
 }
}

Step 10: Run the project and check the database.


You may also like this:

  1. Hibernate with Annotations