Friday, 13 May 2016

Hibernate tutorial with xml configurations

Background

Hibernate is Java ORM (Object relation mapping) tool. It like other ORMs help map Java domain objects with tables in relational databases. It removes the overhead of using the underlying JDBC calls. It supports CRUD operations across all major relational databases. It supports transaction management and many other features. In this post we will see a demo example of hibernate application.


Architecture


Setup

I am simply going to create a simple standalone Java application using hibernate that used oracle database to connect to.  Also I am using Eclipse IDE with Apache Ivy dependency management tool. So create a project called HibernateDemo. It's structure will be as follows - 



Next lets create required files one by one. Lets start with the table creation. Following SQL should create the desired table for us in oracle - 

 CREATE TABLE Employee (

  id number(10) NOT NULL PRIMARY KEY,

  name varchar2(20) DEFAULT NULL,

  gender varchar2(20) DEFAULT NULL,

  accesstime_time DATE DEFAULT (sysdate)

);

 Next you will need some dependency jars like hibernate, slf4j etc. Add following dependency in ivy file - 

<?xml version="1.0" encoding="ISO-8859-1"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one
   or more contributor license agreements.  See the NOTICE file
   distributed with this work for additional information
   regarding copyright ownership.  The ASF licenses this file
   to you under the Apache License, Version 2.0 (the
   "License"); you may not use this file except in compliance
   with the License.  You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing,
   software distributed under the License is distributed on an
   "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
   KIND, either express or implied.  See the License for the
   specific language governing permissions and limitations
   under the License.    
-->
<ivy-module version="2.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:noNamespaceSchemaLocation="http://ant.apache.org/ivy/schemas/ivy.xsd">
    <info
        organisation="ofsg.com"
        module=""
        status="integration">
    </info>
    
    <dependencies>
        <dependency org="org.hibernate" name="hibernate-core" rev="5.1.0.Final"/>
        <dependency org="org.slf4j" name="slf4j-simple" rev="1.7.21"/>
    </dependencies>
    
    
</ivy-module>

You will also need to manually add oracle OJDBC jar in the classpath.

Java Code and configurations


Next lets create our persistent Java class - Employee.java


package com.osfg.models;


import java.util.Date;

/**
 * 
 * @author athakur
 * 
 */
public class Employee {

    private int id;
    private String name;
    private String gender;
    private Date accessTime;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getAccessTime() {
        return accessTime;
    }

    public void setAccessTime(Date accessTime) {
        this.accessTime = accessTime;
    }

}



Next lets create configuration files that map this class to the database table - employee.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="com.osfg.models.Employee" table="EMPLOYEE">
        <id name="id" type="int">
            <column name="ID" />
            <generator class="assigned" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="NAME" />
        </property>
        <property name="gender" type="java.lang.String">
            <column name="GENDER" />
        </property>
        <property name="accessTime" type="timestamp">
            <column name="ACCESS_TIME" />
        </property>
    </class>
</hibernate-mapping>



NOTE : Notice the generator class. It is set to assigned so that you manually assign the primary key. There are many generator classes such as assigned (It is used if id is specified by the user), increment, hilo, sequence, native etc.

Now lets see the hibernate configuration file that has database connection details - hibernate.cfg.xml

<?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="hbm2ddl.auto">update</property>  
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>  
<property name="connection.url">jdbc:oracle:thin:@localhost:1699/test</property>  
<property name="connection.username">system</property>  
<property name="connection.password">test</property>  
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>  
<mapping resource="/com/osfg/resources/employee.hbm.xml"/>  
</session-factory>  
  
</hibernate-configuration>  


And now finally write the demo code to demonstrate the functionality - HibernateDemo.java

package com.osfg.main;

import java.util.Date;

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

import com.osfg.models.Employee;

/**
 * 
 * @author athakur
 * 
 */
public class HibernateDemo {

    public static void main(String args[]) {

        Configuration cfg = new Configuration();
        cfg.configure("/com/osfg/resources/hibernate.cfg.xml");
        SessionFactory sFactory = cfg.buildSessionFactory();
        Session session = sFactory.openSession();
        Transaction transaction = session.beginTransaction();

        Employee newEmployee = new Employee();
        newEmployee.setId(1);
        newEmployee.setName("Aniket");
        newEmployee.setGender("male");
        newEmployee.setAccessTime(new Date());

        session.persist(newEmployee);

        transaction.commit();
        session.close();

        System.out.println("Employee record successfully saved");

    }

}

And you should be all set. Just run as any other Java application.






Related Links


No comments:

Post a Comment

t> UA-39527780-1 back to top