Search This Blog

Hibernate introduction

Hibernate is popular open source object relational mapping tool for Java platform. It provides powerful, ultra-high performance object/relational persistence and query service for Java.
Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework.
Hibernate takes care of the mapping from Java classes to database tables and also provides data query and retrieval facilities. Hibernate significantly reduces development time in the software projects.
Hibernate is an open source object/relational mapping tool for Java. Hibernate lets you develop persistent classes following common Java idiom - including association, inheritance, polymorphism, composition and the Java collections framework.
Hibernate not only takes care of the mapping from Java classes to database tables (and from Java data types to SQL data types), but also provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.
Hibernates goal is to relieve the developer from 95 percent of common data persistence related programming tasks.
Hibernate is Free Software. The LGPL license is sufficiently flexible to allow the use of Hibernate in both open source and commercial projects (see the LicenseFAQ for details). Hibernate is available for download at http://www.hibernate.org/. This tutorial aims to provide insight into Hibernate version 3.0RC and its usage Some of the main features of hibernate are listed below and we have tried to explain some of them in detail later in this tutorial.
Transparent persistence without byte code processing
Transparent persistence
JavaBeans style properties are persisted
No build-time source or byte code generation / processing
Support for extensive subset of Java collections API
Collection instance management
Extensible type system
Constraint transparency
Automatic Dirty Checking
Detached object support
Object-oriented query language
Powerful object-oriented query language
Full support for polymorphic queries
New Criteria queries
Native SQL queries
Object / Relational mappings
Three different O/R mapping strategies
Multiple-objects to single-row mapping
Polymorphic associations
Bidirectional associations
Association filtering
Collections of basic types
Indexed collections
Composite Collection Elements
Lifecycle objects
Automatic primary key generation
Multiple synthetic key generation strategies
Support for application assigned identifiers
Support for composite keys
Object/Relational mapping definition
XML mapping documents
Human-readable format
XDoclet support
HDLCA (Hibernate Dual-Layer Cache Architecture)
Thread safeness
Non-blocking data access
Session level cache
Optional second-level cache
Optional query cache
Works well with others
High performance
Lazy initialization
Outer join fetching
Batch fetching
Support for optimistic locking with versioning/timestamping
Highly scalable architecture
High performance
No ?special? database tables
SQL generated at system initialization time
(Optional) Internal connection pooling and PreparedStatement caching
J2EE integration
JMX support
Integration with J2EE architecture (optional)
New JCA support 

List of Dialect use in hibernate

DB2 - org.hibernate.dialect.DB2Dialect
HypersonicSQL - org.hibernate.dialect.HSQLDialect
Informix - org.hibernate.dialect.InformixDialect
Ingres - org.hibernate.dialect.IngresDialect
Interbase - org.hibernate.dialect.InterbaseDialect
Pointbase - org.hibernate.dialect.PointbaseDialect
PostgreSQL - org.hibernate.dialect.PostgreSQLDialect
Mckoi SQL - org.hibernate.dialect.MckoiDialect
Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect
MySQL - org.hibernate.dialect.MySQLDialect
Oracle (any version) - org.hibernate.dialect.OracleDialect
Oracle 9 - org.hibernate.dialect.Oracle9Dialect
Progress - org.hibernate.dialect.ProgressDialect
FrontBase - org.hibernate.dialect.FrontbaseDialect
SAP DB - org.hibernate.dialect.SAPDBDialect
Sybase - org.hibernate.dialect.SybaseDialect
Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect

Access the Private method from outside class in Java

You can access private method from outside class by changing the runtime behavior of the class

public method getDeclareMethod(String name,Class[] parameterTypes) throws NoSuchMethodException,SecurityException : returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

 

public class DynamicClass {

private void show(){
System.out.println("Test");
}
}

import java.lang.reflect.Method;

public class AccessPrivateMethod {

public static void main(String args[]){
try{
Class clsClass = Class.forName("DynamicClass");
Object o = clsClass.newInstance();
Method method = clsClass.getDeclaredMethod("show", null);
method.setAccessible(true);
method.invoke(o, null);
}catch(Exception e){
e.printStackTrace();
}

}
}


Result : Test

Hibernate Simple Example

Process.java
 
package com;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class Process
{
    static Session session=null;
  
    public static void main(String[] args)
    {
        try
        {
            selectAll();
             System.out.println("Done");
        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void insert(String name)
    {
        session = HibernateUtil.getSessionFactory().openSession();
         EmpBean empBean=new EmpBean();
         System.out.println("Inserting Record");
         session.beginTransaction();
      
         empBean.setName(name);
      
         session.save(empBean);
         session.getTransaction().commit();
         HibernateUtil.getSessionFactory().close();
    }
    public static void selectAll()
    {
        session = HibernateUtil.getSessionFactory().openSession();
        Query query=session.createQuery("from EmpBean"); // EmpBean is a Class name which is created..
        List rs=query.list();
        for(int i=0;i<rs.size();i++)
        {
            EmpBean e=(EmpBean) rs.get(i);
            System.out.println("Name  :" +e.getName());
            System.out.println("Id  :" +e.getId());

        }
        HibernateUtil.getSessionFactory().close();
    }

}
 
HibernateUtil.java
 
package com;

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

public class HibernateUtil
{
    private static final SessionFactory sessionFactory = buildSessionFactory();
  
    private static SessionFactory buildSessionFactory()
    {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration config=new Configuration().addResource("hibernate.cfg.xml"); 
// hibernate.cfg.xml is hibernate cofiguration file you can give your xml file..
            return config.configure().buildSessionFactory();
        }
        catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
 
EmpBean.java
 
package com;

public class EmpBean
{
    private Long id=new Long(10);;
    private String name;
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }  

}
 
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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
        <property name="connection.url">jdbc:oracle:thin:@localhost:1521:oracle</property>
        <property name="connection.username">jatin</property>
        <property name="connection.password">jatin</property>

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

        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.OracleDialect</property>
        <!-- dialect for common query generate by Hibernate -->
        <!-- Enable Hibernate's current session context -->
        <property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>

        <property name="hibernate.cache.use_second_level_cache">false</property>
        <property name="hibernate.cache.use_query_cache">false</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>
      
        <!-- Mapping files -->
        <mapping resource="EmpBean.hbm.xml"/>
          <!-- EmpBean.hbm.xml is file for EmpBean class , give any name... -->
    </session-factory>
</hibernate-configuration>
 
EmpBean.hbm.xml
 
<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 2.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping>
    <class name="com.EmpBean" table="EMPLOYEE" dynamic-update="true" dynamic-insert="true">
        <cache usage="read-write"/>
         <id name="id" column="EMPID" type="java.lang.Long">
            <generator class="increment" ></generator>
        </id>
     
      
        <property name="name" type="java.lang.String" update="true" insert="true" access="property" column="EMPNAME"/>
    </class>
</hibernate-mapping>
 
 
index.jsp
 
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  
    <title>Hibernate Page</title>
  
  </head>

  <body>
  <form action="insert.jsp" >
    <table>
        <tr>
            <td>Emp Name : </td>
            <td><input type="text" name="empname"></td>
        </tr>
        <tr>
            <td><input type="submit" value="Insert" name="submit">
                <input type="reset" value="cancel" name="reset">
            </td>
        </tr>
    </table>
    </form>
  </body>
</html>
 
insert.jsp
 
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%@page import="com.Process;"%>


<%
new Process().insert(request.getParameter("empname"));
request.getRequestDispatcher("index.jsp").forward(request,response);
%>
List of Jar which is needed for run this example
hibernate.jar
ojdbc14.jar

Create Query in Hibernate

To create query in the Hibernate ORM framework, there is three different types. The folloing are the three ways to create query instance:
  • 1)session.createQuery()
  • 2)session.createSQLQuery()
  • 3)session.createCriteria()
We will look into the details of each category in detail.

session.createQuery()

The method createQuery() creates Query object using the HQL syntax. Fro example
 
Query query = session.createQuery("from Student s where s.name 
like 'k%'");

session.createSQLQuery()

The method createSQLQuery() creates Query object using the native SQL syntax. Fro example
 
Query query = session.createQuery("Select * from Student");

session.createCriteria()

The method createCriteria() creates Criteria object for setting the query parameters. This is more useful feature for those who don't want to write the query in hand. You can specify any type of complicated syntax using the Criteria API.
 
Criteria criteria = session.createCriteria(Student.class);

JDBC 4.0 New Features (JDK 1.6)

This article provides an introduction to the array of core new features available in JDBC 4.0.
The java.sql and javax.sql are the primary packages for JDBC 4.0
New Feature:
Auto- loading of JDBC driver class: In JDBC 4 invoking the getConnection() on DriverManager will automatically load a driver. Upon loading the driver, an instance of the driver is created and the registerDriver() method is invoked to make that driver available to clients. 
In earlier versions of JDBC, applications had to manually register drivers before requesting Connections. With JDBC 4.0, applications no longer need to issue a Class.forName() on the driver name; instead, the DriverManager will find an appropriate JDBC driver when the application requests a Connection.

SQL exception handling enhancements: JDBC 4 addresses the error handling beautifully. As databases are often remotely accessible resources, problems such as network failures is common and it can cause exceptions when executing a database operation. SQL statements can also cause exceptions. Prior to JDBC 4, most JDBC operations generated a simple SQLException.

SQLXML support: SQLXML is a mapping in the Java programming language for the XML data type in SQL. XML is a built-in type that stores an XML value as a column value in a row of the target table. By default, drivers implement an SQLXML object as a logical pointer to the XML data rather than the data itself. An SQLXML object is valid for the duration of the transaction in which it was created.

Support for RowId data type: JDBC introduces  support for ROWID, a data type that had been in use in database products even before it became part of the SQL.

Connection management enhancements: In jdbc it may happen that a Connection is lying idle or not closed in a pool, then it became stale over time. This will led to the connection pool run out of resources due to stale connection. We know that the stale connection doesn't mean that a connection is closed. Now in JDBC 4 Connection class we have provided one method isValid(), which allows a client to query the database driver if a connection is still valid. As database is a shared resource, so many application can access the same data store. To maintain all the records of the client is a difficult task, now in JDBC 4 an application can associate metadata with a database connection via the setClientInfo() method, which takes a name/value pair, or a Properties object. 

DataSet implementation of SQL using Annotations: The JDBC 4.0 specification leverages annotations to allow developers to associate a SQL query with a Java class without a need to write a lot of code to achieve this association.

Enhanced BLOB/CLOB functionality
National character set support

Note:  This features only available from JDK 1.6 onwards.

Upload Image into database with Java

In this article, I am going to describe how to upload images to an Oracle database using an java. below are steps for do this.

1. Create table which have a blob data type.
2. Write java program.

Let's see how to insert image into database.Here is the explanation

Create table using oracle database.

Create table image
(
name varchar2(20),
photo blob
);

Java Program



import java.sql.*;
import java.io.*;

public class ImageWriter {

static Connection connection = null;
static CallableStatement pstat = null;
static String connectionURL = null;

public static void main(String[] args) {
try{
Class.forName("oracle connection class");
connection = DriverManager.getConnection("connection url", "username", "password");

PreparedStatement pstat = connection.prepareStatement("insert into image(name,photo) values(?,?)");

FileInputStream fin = new FileInputStream("D:\\test.jpg");
pstat.setString(1, "ABC");
pstat.setBinaryStream(2, fin, fin.available());

int result = pstat.executeUpdate();
System.out.println(result + " Record Successfully Inserted");

connection.close();

}catch(Exception e){
e.printStackTrace();
}

}

}


Result : 1 Record Successfully Inserted

Retrieve Image from database with Java

In this article, I am going to describe how to retrieve images from database (Oracle database) using an java.
Let’s see how to retrieve image from database.
Here is explanation.

Java Program


import java.sql.*;
import java.io.*;

public class RetrieveImage{

static Connection connection = null;
static CallableStatement pstat = null;
static String connectionURL = null;

public static void main(String[] args) {

try{
Class.forName("Oracle Connection Class");
connection = DriverManager.getConnection("connection url","username", "password");

PreparedStatement pstat = connection.prepareStatement("Select name,photo from image");

ResultSet rs = pstat.executeQuery();
rs.next(); // go to first row
Blob b = rs.getBlob(2);
byte[] bt = new byte[(int) b.length()];
bt = b.getBytes(1, (int)b.length());

FileOutputStream fout = new FileOutputStream("D:\\test.jpg");
fout.write(bt);
fout.close();

System.out.println("Done");

connection.close();

}catch(Exception e){
e.printStackTrace();
}

}

}


Resule: Done

Java Performance and best coding Tips

1.        Try, catch block should not be in loop (unless specifically required).

2.     All Collection API Classes should be specifically reinitialized to null (since JVM has to specifically do it & GC spends much time in doing these functions).

3.        Release JDBC resources when done with tasks.

4.        Use inner join instead of multiple queries.

5.        Optimize SQL queries.

6.        Always use Dynamic SQL (Prepare Statement) rather than the static SQL like Statement.

7.        Try to avoid repeated DB calls to retrieve the same data. Instead of that retrieve the data from the table and keep the data in Java objects and use that in the subsequent call. (make Model class for that and use getter, setter methods)

8.        Avoid Select * instead give the names of fields to be selected in query (e.g. Select id,name from Student).
9.        Using getXX(int ColumnIndex) instead of getXX(String columnName): Depending upon the no of columns in your resultSet, a getXX field operation using column Index is two times as fast as than using Column Name.

10.     Do not use Vectors, instead of that use Collection classes like ArrayList.

11.     Avoid using method call as loop termination test. E.g. Don’t use list.size(), instead use store that in a temporary variable and then use the temporary variable for testing loop termination test.

12.     Avoid throwing Exception in normal flow of execution since try-catch-finally block is costly.

13.     Build proper WHERE clause in SQL SELECT for database indexing. (In left of Join select table with less no of records).

14.     Try using java Collection classes instead of array.

15.     String Concatenation: Check that For String concatenation use StringBuilder (JDK 1.5 has StringBuilder over StringBuffer) instead of String ‘+’ operator.

16.     Debugging Statements: Do not use System.out.println or printstackTrace(). Use log4j.debug() for debugging. In catch blocks add log4.error() wherever applicable.

17.     Prepare Statement: Use prepared statement for retrieving data when we have parameterized queries(insert, update, delete) else use statements.

18.     Avoid object instantiation inside Loop. If possible create object outside loop and reuse the same object inside the loop.

19.     Minimize object lifetimes. Keep the lifetimes of your data as short as possible. Place the declaration in the most nested block that first uses the data. If operator new is used, do the new just before the first use, and the set the reference to null just after the last use.

20.     Minimum use of Session variables in the code instead set variables in Request. Set session variables as null after use.

21.     The constants are not static we can make it final for better performance(e.g. if we have fix value for variable than make it final private void testMethod(final int id){}).

22.     Apply Transactions wherever necessary.

23.     Apply Query Caching if is required as per functionality.

24.     Minimize data conversions or Castings

25.     Try to use primitive java objects instead Wrapper classes as like Wrapper classes (i.e. Integer) allocate large data amounts in memory.

26.     Replace a long if-else-if chain by a switch if possible; this is much faster.

27.     Declaring a method as private, final, or static makes calls to it faster. Of course, you should only do this when it makes sense in the application.

28.     Do not add JavaScript directly in the JSP Code; instead include JS File and include in Jsp (e.g <script src=”include/common.js”></script>).

29.     Use STRUTS, JSTL specific UI Tag Library in JSP pages.

30.     Exceptions are taken care in the code and highest levels of Exceptions are routed to Error Page; others are properly logged using logger.