Search

Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

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

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 

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);

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.


Hibernate Examples


Example

Source

Hibernate Tools Example
Download
Hibernate Annotations Example
Download
Hibernate Many-To-One Mapping Example
Download
Hibernate One-To-One Mapping Example
Download
Hibernate One-To-Many Mapping Example
Download
Hibernate Many-To-Many Mapping Example
Download
Hibernate Component Mapping Example
Download
Hibernate Many-To-One Mapping Using Annotations Example
Download
Hibernate One-To-One Mapping Using Annotations Example
Download
Hibernate One-To-Many Mapping Using Annotations Example
Download
Hibernate Many-To-Many Mapping Using Annotations Example
Download
Hibernate Component Mapping Using Annotations Example
Download


Hibernate Annotations Example

This example is the same as the first example except that it uses annotations. There we first started by creating the .hbm.xml file, here there is no need to create it instead we will use annotations to do the object relational mapping.
In addition to the already existing jar files you need to add the following jar files to the classpath.
1.hibernate-commons-annotations.jar
2.ejb3-persistence.jar
3.hibernate-annotations.jar
Here we first start by creating the Course class. The Course class is shown below.
01.package com.vaannila.course;
02. 
03.import javax.persistence.Column;
04.import javax.persistence.Entity;
05.import javax.persistence.GeneratedValue;
06.import javax.persistence.Id;
07.import javax.persistence.Table;
08. 
09. 
10.@Entity
11.@Table(name="COURSES")
12.public class Course {
13. 
14.private long courseId;
15.private String courseName;
16. 
17.public Course() {
18.}
19. 
20.public Course(String courseName) {
21.this.courseName = courseName;
22.}
23. 
24.@Id
25.@GeneratedValue
26.@Column(name="COURSE_ID")
27.public long getCourseId() {
28.return this.courseId;
29.}
30. 
31.public void setCourseId(long courseId) {
32.this.courseId = courseId;
33.}
34. 
35.@Column(name="COURSE_NAME", nullable=false)
36.public String getCourseName() {
37.return this.courseName;
38.}
39. 
40.public void setCourseName(String courseName) {
41.this.courseName = courseName;
42.}
43. 
44.}
As you can see we have used annotations in the code to do the object relational mapping. Hibernate supports EJB 3 persistence annotations. The EJB 3 annotations are contained in thejavax.persistence package. If you avoid using Hibernate specific features in your application, then you will have the freedom to deploy your application in any environment that supports EJB 3. Anything imported from javax.persistence package tree is EJB 3 supported and anything imported fromorg.hibernate package tree is Hibernate specific.
The @Entity annotation is used to mark this class as an Entity bean. So the class should atleast have a package scope no-argument constructor.
The @Table annotation is used to specify the table to persist the data. The name attribute refers to the table name. If @Table annotation is not specified then Hibernate will by default use the class name as the table name.
The @Id annotation is used to specify the identifier property of the entity bean. The placement of the@Id annotation determines the default access strategy that Hibernate will use for the mapping. If the@Id annotation is placed over the field, then filed access will be used. Instead if it placed over the getter method of that field, then property access will be used. Here we use property access.
The @GeneratedValue annotation is used to specify the primary key generation strategy to use. If the strategy is not specified by default AUTO will be used.
The @Column annotation is used to specify the details of the column to which a field or property will be mapped. Here the courseId property is mapped to COURSE_ID column in the COURSES table. If the @Column annotation is not specified by default the property name will be used as the column name.
The next change you need to do here is, instead of adding the .hbm.xml file to the hibernate.cfg.xmlfile, we add the fully qualified name of the annotated class to the mapping element.
01.<?xml version="1.0" encoding="UTF-8"?>
02.<!DOCTYPE hibernate-configuration PUBLIC
03."-//Hibernate/Hibernate Configuration DTD 3.0//EN"
05.<hibernate-configuration>
06.<session-factory>
07.<property name="hibernate.connection.driver_class"> org.hsqldb.jdbcDriver</property>
08.<property name="hibernate.connection.url"> jdbc:hsqldb:hsql://localhost<;/property>
09.<property name="hibernate.connection.username">sa</property>
10.<property name="connection.password"></property>
11.<property name="connection.pool_size">1</property>
12.<property name="hibernate.dialect"> org.hibernate.dialect.HSQLDialect</property>
13.<property name="show_sql">true</property>
14.<property name="hbm2ddl.auto">create</property>
15.<mapping class="com.vaannila.course.Course" />
16.</session-factory>
17.</hibernate-configuration>
The SessionFactory should be configured using the AnnotationConfiguration object instead of theConfiguration object used with XML mappings.
01.package com.vaannila.util;
02. 
03.import org.hibernate.SessionFactory;
04.import org.hibernate.cfg.AnnotationConfiguration;
05. 
06.public class HibernateUtil {
07.private static final SessionFactory sessionFactory;
08.static {
09.try {
10.sessionFactory = new AnnotationConfiguration().configure()
11..buildSessionFactory();
12.catch (Throwable ex) {
13.System.err.println("Initial SessionFactory creation failed." + ex);
14.throw new ExceptionInInitializerError(ex);
15.}
16.}
17. 
18.public static SessionFactory getSessionFactory() {
19.return sessionFactory;
20.}
21.}
These are the only few changes you need to do to make the example work using annotations. Now the big question is should you use annotations?
If your answer is yes to the following questions then you can use annotations in your project.
·         Do you have the flexibility to use Java 5 Environment?
·         Do you have the knowledge of which production database you are going to use? If yes, you can use annotations, this brings in strong coupling. Inorder to support multiple databases, it is better to have the mapping information in a seperate xml file rather than using annotations. You can easily have multiple xml files each specific for a particular database rather than having a different sets of source codes.
Instead than keeping the mapping informations in a seperate file, using annotations you can always keep them along with the source code, in this way the soure code and mapping information will always be in sync.
Download Spring examples source code