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

Monday, October 10, 2016

Hibernate show sql with parameter values

In this article i will show you "How to log the SQL with parameters in Hibernate?"

As we know Hibernate is ORM framework which is being used at persistence layer. If you are a developer and you are Woking on development environment than i guess you faced a challenge to debug the SQL statement. 


Hibernate gives us a feature to show sql in the logs 



But the above feature doesn't let see the parameters which you are passing into your SQL statement. 


Hibernate provides 2 category and levels to execute the SQL parameters and show their bind parameters.


1. Use org.hibernate.SQL as debug

2. org.hibernate.type.descriptor.sql as trace

Here is the code snippet of log4j : - 



Please have look on the logs where you can see the actual parameters are being printed 




Employee entity used in the code : - 




Main class : - 




Summary :-


So using "log4j.logger.org.hibernate.SQL=debug" and "log4j.logger.org.hibernate.type.descriptor.sql=trace" we can easily log SQL parameters. With these features it is really easy to trouble shoot or debug the issue on development environment. But always remember it is always being advisable in the development or sand box environment. Please do not use this features on production environment because it will generate a lot of unnecessary logs and may creak disk space issue in the long run.

Friday, July 17, 2015

What is Hibernate SessionFactory?

Hibernate SessionFactory : – SessionFactory is interface which is available in the "org.hibernate" pakcage of the Hibernate distribution.
 There are some key points regarding the SessionFactory : -
1.Single Data Store : – It is single data store for your whole application. Although you can have multiple SessionFactory but each SessionFactory will have one different database associated with it.

2.Thread Safe : – SessionFactory is thread safe so due to this feature many thread can access the SessionFactory.

 3.Immutable : - Once the SessionFactory's object is created you can not change or set the values of Session Facotyr. Its internal state is set at the time of creation.

 4.Singleton : – SessionFactory is built at the time of application startup and it follows the singleton design pattern.

Q.How to create the SessionFactory ?

Ans : Lets assume you have MYSQL database which you are using in your application than for creating the SessionFactory you will write following java code : -
Configuration cfg=new Configuration();

Configuration cfg1=cfg.configure(“hibernate.cfg.xml”);

SessionFactory sf1=cfg1.builed SessionFactory();

Line 1 : – Creates empty configuration object
Line 3 : – When you call cfg.configure("hibernate.cfg.xml") it looks for hibnernate.cfg.xml for Hibernate Mapping
 Line 5 : – SessionFacotry Object will be created and will be used by multiple users for long time

Q.How to create the Multiple SessionFactory ? Ans : So for creating multiple SessionFactory you can different cfg.xml file representing your different database. Lets assume you have two databases MYSQL and ORACLE than i will create two cfg.xml file mysql.cfg.xml oracle.cfg.xml And than for SessionFactory i will write the following code
Configuration cfg=new Configuration();

//For MYSQL

databaseConfiguration cfg1=cfg.configure(“mysql.cfg.xml”);

SessionFactory sf1=cfg1.builed SessionFactory();

//For Oracle

databaseConfiguration cfg2=cfg.configure(“oracle.cfg.xml”);

SessionFactory sf2=cfg2.builed SessionFactory();

Hope you have liked the above article. Please put your suggestions and questions and i will try to sort it out….

Thursday, July 16, 2015

Hibernate setup in eclipse

So here is our first step to configure the Hibernate with our java application and create a simple program to insert some value into the database. So follow the following steps : -
TASK : - Create a basic table and insert some values in it using hibernate. Now you would be wondering from where to start so do not worry follow the steps one by one and you will be good to go…..
Step 1: – Download the following library files for hibernate

  • antlr-2.7.6.jar
  • commons-collections-3.1.jar
  • dom4j-1.6.1.jar,hibernate3.jar
  • javassist-3.4.GA.jar
  • jta-1.1.jar
  • mysql-connector-java-5.1.17-bin.jar
  • ojdbc14.jar
  • slf4j-api-1.4.2.jar
  • slf4j-simple-1.5.2.jar 

Step 2: - Goto Eclipse File -> New create new Java Project with the any name you want
Step 3: - Once you are done with creating the project on high level we will be creating the following JAVA Classes and XML files

  • hibernate.cfg.xml
  • Person.hbm.xml
  • HibernateUtil.java
  • Person.java
  • PersonDAO.java
  • TestHibernate.java (To test our application)
Step 4: - Once you are done with above setup in eclipse your project structure will look like this 

 

Step 5: - Now in our current example we are using MYSQL database as a back end so we will have following table: -

  • Schema Name :  – hibernate_example
  • Table Name : – person
  • SQL Script for Table : -

DROP TABLE IF EXISTS `hibernate_example`.`person`; CREATE TABLE  `hibernate_example`.`person` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `first_name` varchar(45) NOT NULL, `last_name` varchar(45) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
Step 6 : - hibernate.cfg.xml

 
    
             
        com.mysql.jdbc.Driver
        jdbc:mysql://localhost:3306/hibernate_example
        root
        root      
        org.hibernate.dialect.MySQL5Dialect
         
        
        1
         
        
        thread
 
        
        true
        false
 
        
        
    
     

Step 7 : – Person.hbm.xml

    
     
        
            
        
         
        
             
        
         
    

Step 8 : – HibernateUtil.java
package com.hibernate.util;
 
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
 
/**
 * Hibernate Utility used to configure Hibernate's Session Factory and retrieve
 * it.
 */
public class HibernateUtil {
 
    private static final SessionFactory sessionFactory;
 
    static {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            // ------ --- -------------- ---- -----------------
            sessionFactory = new Configuration().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);
        }
    }
 
    /**
     * Get the configured session factory
     * 
     * @return session factory
     */
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
Step 9 : – Person.java
package com.hibernate.enity;
 
public class Person {
     
    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 10 : – PersonDAO.java
package com.hibernate.dao;
 
import org.hibernate.Session;
import org.hibernate.Transaction;
 
import com.hibernate.enity.Person;
import com.hibernate.util.HibernateUtil;
 
 
public class PersonDAO {
     
    public void saveOrUpdatePerson(Person personObj){
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
         
        //begin the transaction
        Transaction trans=session.beginTransaction();
         
        //Save the person in database
        session.saveOrUpdate(personObj);
         
        //Commit the transaction
        trans.commit();
    }
 
}
Step 11 : – TestHibernate.java
package com.hibernate.test;
 
import com.hibernate.dao.PersonDAO;
import com.hibernate.enity.Person;
 
public class TestHibernate {
     
    public static void main(String args[]){
         
        //1.Create the object of the Person class
        Person personObj = new Person();
         
        //2.Set the values which you want to save in the database
        personObj.setFirstName("Rahul");
        personObj.setLastName("Wagh");
         
        //3.Create the object of the DAO class which will insert our person object to TABLE
        PersonDAO personDAOObj = new PersonDAO();
        personDAOObj.saveOrUpdatePerson(personObj);
         
         
    }
}
So we good to just goto TestHibernate.java class and do Right click and select Run as Java Application. Make sure your database is running. Please post your comments and suggestions about the aritcle.

What is Hibernate ORM(object-relational mapping)?

Hibernate ORM ( Object Relational Mapping) in the short form called as Hibernate is a framework which is being used for performing all the tasks which are related to Database operations.
So seems like quite complex but do not worry just go through the following points and than you will get to know more above Hibernate : -
  1. OOP : -Main aim of hibernate is to convert the basic SQL queries and operations which we do into the Object Oriented Paradigm.
  2. JAVA POJO(Plain Old Java Object) : - All of your database table will be represented with the JAVA class know as POJO(Plain Old Java Object)
  3. NO SQL : - So you do not have to deal with SQL queries all you need is to play with the JAVA POJO classes.
  4. HQL(Hibernate Query Language) : -Hibernate provides HQL (Hibernate Query Language) which is much a like SQL(Structured Query Language) for writing the database queries for performing Database operations.
  5. INTEGRATION : – Hibernate is quite good at integration and it can be integrated with any JAVA, JAVA EE, EJB, JBI application.
If you are new to the Hibernate and beginner in the JAVA than it will look like a lot in your plate to eat. But do not worry we will have each bite one by one. So seat tight we have lot of topics which will explain you how to start working with the Hibernate.