Hibernate Example

Below is the working example of Hibernate 4.0 with oracle 11g express edition as database.

Create Table:

create table EMPLOYER
(
  id         NUMBER not null,
  first_name VARCHAR2(20),
  last_name  VARCHAR2(20),
  salary     INTEGER
)


Java Code:

Step1: Create New Maven Project HibernateExample
Step2: Create pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.hibernate</groupId>
  <artifactId>HibernateExample</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>HibernateExample</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.common</groupId>
            <artifactId>hibernate-commons-annotations</artifactId>
            <version>4.0.1.Final</version>
            <classifier>tests</classifier>
        </dependency>
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.0-api</artifactId>
            <version>1.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.0.1.Final</version>
        </dependency>
        <dependency>
            <groupId>com.oracle</groupId>
            <artifactId>ojdbc6</artifactId>
            <version>11.2.0</version>
        <!--     <systemPath>"C:/oraclexe/app/oracle/product/11.2.0/server/jdbc/lib/ojdbc6.jar"</systemPath> -->
        </dependency>
        <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
</dependency>
  </dependencies>
</project>

Step3: Create pojo class

package com.hibernate.HibernateExample;

import java.io.*;

public class Employee implements Serializable {
    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private int id;
    private String firstName;
    private String lastName;  
    private int salary; 

    public Employee() {}
    public Employee(int id,String fname, String lname, int salary) {
        this.id=id;
        this.firstName = fname;
        this.lastName = lname;
        this.salary = salary;
    }
    public int getId() {
        return id;
    }
    public void setId( int id ) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName( String first_name ) {
        this.firstName = first_name;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName( String last_name ) {
        this.lastName = last_name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary( int salary ) {
        this.salary = salary;
    }
}

Step4: Create hbm.xml file

<?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 package="com.hibernate.HibernateExample">
   <class  name="Employee" table="EMPLOYER">
      <meta attribute="class-description">
         This class contains the employee detail.
      </meta>
      <id name="id" type="int" column="ID">
         <generator class="native"/>
      </id> 
      <property name="firstName" column="FIRST_NAME" type="string"/>
      <property name="lastName" column="LAST_NAME" type="string"/>
      <property name="salary" column="SALARY" type="int"/>
   </class>
</hibernate-mapping>

Step5: Create cfg.xml file

<?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>

<!-- Related to the connection START -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<!-- <property name="connection.url">jdbc:oracle:thin:localhost:1521:XE</property> -->
<property name="connection.url">jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname) (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE)))</property>
<property name="connection.username">username</property>
<property name="connection.password">password</property>
<!-- Related to the connection END -->

<!-- Related to hibernate properties START -->
<property name="show_sql">true </property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
 <property name="hbm2ddl.auto">update </property>
<!-- Related to hibernate properties END -->

<!-- Related to mapping START -->
<mapping resource="Employee.hbm.xml"/>
<!-- Related to the mapping END -->

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

Step6: Create Main class

package com.hibernate.HibernateExample;

import java.util.List;
import java.util.Date;
import java.util.Iterator;




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

public class ManageEmployer {
   private static SessionFactory factory;
  // private static SessionFactory sessionFactory;
   private static ServiceRegistry serviceRegistry;
  
public static void main(String[] args) {
      try{
        // factory = new Configuration().configure().buildSessionFactory();
        
        
        
         Configuration configuration = new Configuration();
         configuration.configure("hibernate.cfg.xml");
         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);
      }
   ManageEmployer ME = new ManageEmployer();

      /* Add few employee records in database */
      Integer empID1 = ME.addEmployer(1,"Anand", "Kumar", 100000);
      Integer empID2 = ME.addEmployer(2,"Srinivas", "Das", 200000);
      Integer empID3 = ME.addEmployer(3,"Michael", "Paul", 300000);

     
      /* List down all the employers */
     ME.listEmployees();

      /* Update employee's records */
     ME.updateEmployer(empID1, 5000);

      /* Delete an employer from the database */
      ME.deleteEmployer(empID2);

      /* List down new list of the employers */
      ME.listEmployees();
   }
 
   /* Method to  READ all the employees */
   public void listEmployees( ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         List employees = session.createQuery("FROM Employee").list();
         for (Iterator iterator =
                           employees.iterator(); iterator.hasNext();){
            Employee employee = (Employee) iterator.next();
            System.out.print("First Name: " + employee.getFirstName());
            System.out.print("  Last Name: " + employee.getLastName());
            System.out.println("  Salary: " + employee.getSalary());
         }
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
   }
   /* Method to UPDATE salary for an employee */
   public void updateEmployer(Integer EmployerID, int salary ){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employee =
                    (Employee)session.get(Employee.class, EmployerID);
         employee.setSalary( salary );
         session.update(employee);
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
   }
  
  
   /* Method to CREATE an employer in the database */
   public Integer addEmployer(int id,String fname, String lname, int salary){
      Session session = factory.openSession();
      Transaction tx = null;
      Integer employeeID = null;
      try{
         tx = session.beginTransaction();
         Employee employee = new Employee(id,fname, lname, salary);
         employeeID = (Integer) session.save(employee);
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
      return employeeID;
   }
   /* Method to DELETE an employee from the records */
   public void deleteEmployer(Integer EmployeeID){
      Session session = factory.openSession();
      Transaction tx = null;
      try{
         tx = session.beginTransaction();
         Employee employer =
                   (Employee)session.get(Employee.class, EmployeeID);
         session.delete(employer);
         tx.commit();
      }catch (HibernateException e) {
         if (tx!=null) tx.rollback();
         e.printStackTrace();
      }finally {
         session.close();
      }
   }
}


Step7: Execute the main class ManageEmployer.java

O/P:

Feb 22, 2015 7:49:10 PM org.hibernate.annotations.common.Version <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
Feb 22, 2015 7:49:10 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.0.1.Final}
Feb 22, 2015 7:49:10 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Feb 22, 2015 7:49:10 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Feb 22, 2015 7:49:10 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: hibernate.cfg.xml
Feb 22, 2015 7:49:10 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
Feb 22, 2015 7:49:11 PM org.hibernate.cfg.Configuration addResource
INFO: HHH000221: Reading mappings from resource: Employee.hbm.xml
Feb 22, 2015 7:49:11 PM org.hibernate.internal.util.xml.DTDEntityResolver resolveEntity
WARN: HHH000223: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/. Use namespace http://www.hibernate.org/dtd/ instead. Refer to Hibernate 3.6 Migration Guide!
Feb 22, 2015 7:49:11 PM org.hibernate.cfg.Configuration doConfigure
INFO: HHH000041: Configured SessionFactory: null
Feb 22, 2015 7:49:11 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000402: Using Hibernate built-in connection pool (not for production use!)
Feb 22, 2015 7:49:11 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000115: Hibernate connection pool size: 20
Feb 22, 2015 7:49:11 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000006: Autocommit mode: false
Feb 22, 2015 7:49:11 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000401: using driver [oracle.jdbc.driver.OracleDriver] at URL [jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=WhatSheWants) (PORT=1521))(CONNECT_DATA=(SERVICE_NAME=XE)))]
Feb 22, 2015 7:49:11 PM org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
INFO: HHH000046: Connection properties: {user=system, password=****}
Feb 22, 2015 7:49:13 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.Oracle10gDialect
Feb 22, 2015 7:49:13 PM org.hibernate.engine.transaction.internal.TransactionFactoryInitiator initiateService
INFO: HHH000399: Using default transaction strategy (direct JDBC transactions)
Feb 22, 2015 7:49:13 PM org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory <init>
INFO: HHH000397: Using ASTQueryTranslatorFactory
16 [main] INFO org.hibernate.validator.util.Version - Hibernate Validator 4.2.0.Final
Feb 22, 2015 7:49:14 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000228: Running hbm2ddl schema update
Feb 22, 2015 7:49:14 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000102: Fetching database metadata
Feb 22, 2015 7:49:14 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000396: Updating schema
Feb 22, 2015 7:49:14 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000261: Table found: SYSTEM.EMPLOYER
Feb 22, 2015 7:49:14 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000037: Columns: [last_name, id, salary, first_name]
Feb 22, 2015 7:49:14 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000108: Foreign keys: []
Feb 22, 2015 7:49:14 PM org.hibernate.tool.hbm2ddl.TableMetadata <init>
INFO: HHH000126: Indexes: [sys_c007088]
Feb 22, 2015 7:49:14 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute
INFO: HHH000232: Schema update complete
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into EMPLOYER (FIRST_NAME, LAST_NAME, SALARY, ID) values (?, ?, ?, ?)
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into EMPLOYER (FIRST_NAME, LAST_NAME, SALARY, ID) values (?, ?, ?, ?)
Hibernate: select hibernate_sequence.nextval from dual
Hibernate: insert into EMPLOYER (FIRST_NAME, LAST_NAME, SALARY, ID) values (?, ?, ?, ?)
Hibernate: select employee0_.ID as ID0_, employee0_.FIRST_NAME as FIRST2_0_, employee0_.LAST_NAME as LAST3_0_, employee0_.SALARY as SALARY0_ from EMPLOYER employee0_
First Name: Zara  Last Name: Ali  Salary: 5000
First Name: Michael  Last Name: Paul  Salary: 300000
First Name: John  Last Name: Paul  Salary: 10000
First Name: Anand  Last Name: Kumar  Salary: 100000
First Name: Srinivas  Last Name: Das  Salary: 200000
Hibernate: select employee0_.ID as ID0_0_, employee0_.FIRST_NAME as FIRST2_0_0_, employee0_.LAST_NAME as LAST3_0_0_, employee0_.SALARY as SALARY0_0_ from EMPLOYER employee0_ where employee0_.ID=?
Hibernate: update EMPLOYER set FIRST_NAME=?, LAST_NAME=?, SALARY=? where ID=?
Hibernate: select employee0_.ID as ID0_0_, employee0_.FIRST_NAME as FIRST2_0_0_, employee0_.LAST_NAME as LAST3_0_0_, employee0_.SALARY as SALARY0_0_ from EMPLOYER employee0_ where employee0_.ID=?
Hibernate: delete from EMPLOYER where ID=?
Hibernate: select employee0_.ID as ID0_, employee0_.FIRST_NAME as FIRST2_0_, employee0_.LAST_NAME as LAST3_0_, employee0_.SALARY as SALARY0_ from EMPLOYER employee0_
First Name: Zara  Last Name: Ali  Salary: 5000
First Name: Michael  Last Name: Paul  Salary: 300000
First Name: John  Last Name: Paul  Salary: 10000
First Name: Anand  Last Name: Kumar  Salary: 5000


Folder Structure:




No comments:

Post a Comment