Flexible Utilities for Data Retrieval in Hibernate

Introduction

What is Object Relational Mapping?

Maps the Objects in java with the relational entities in the database.
In this,entities/classes refers to table in database,instance of classes.

HibernateStructure

Main Advantages of Object Relational Mappings

Improved productivity:

High-level object-oriented API

Less Java code to write

No SQL to write

Improved performance:

Sophisticated caching

Lazy loading

Eager loading

Improved maintainability:

A lot less code to write

Improved portability:

ORM framework generates database-specific SQL for you

What is Hibernate?

Pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables.

Hibernate Architecture

HibernateArchitecture


Core Interfaces in Hibernate Framework

Session Interface:
Allows to create Query Objects and Retrieve persistant objects.

Not Thread Safe.

Wraps JDBC Connection Factory for Transactions.

eg:
Session session=SessionFactory.openConnection();

SessionFactory Interface

This is a factory that delivers the session objects to hibernate application.
There will be a single SessionFactory for the whole application and it will be shared among all the application threads.
The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime.

    private static final SessionFactory sessionFactory;
    static {
        try {
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

Configuration Interface
This is used to configure hibernate. It’s also used to bootstrap hibernate. Mapping documents of hibernate are located using this interface.


Transaction Interface

Optional interface.
Abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction.

Query and Criteria Interface
This interface allows the user to perform queries and also control the flow of the query execution.


Hibernate Integration with Business Application.

hibernate-diagram

Hibernate Utility For Easy Data Retrieval.

I have designed framework for Data Retrieval using Hibernate Mapping.
This is some kind of experimental task.

User is able extraxct data easily without having much knowledge about Hibernate Queries.

Following are the core features of developed framework.

1. Retrieves Data from Single Table
2. Retrieves Data from Single Table with Condition statement
3. Retrieves Data from Single Table with Condition statement. Get the data from relationship table
4. Joining Two Tables
5. Aggregate function (MIN,MAX)

Utility Files in the Framework

HibernateUtil.java
ba896acb-1

HibernateUtil Source Code : Download

CustomHibernateUtils.java

CustomHibernateUtil

CustomHibernateUtil Source Code : Download

Following are example of usage of developed Utility Components

1. Retrieving data from Single Table

    public void singleTableDataRetrieval() throws Exception {

        List</pre>
<strong>2. Retrieving data from Single Table with Condition statement</strong>


    public void singleTableDataRetrievalWithConditions() {

        Map<String, Object> conditionParmMap = new HashMap<String, Object>();

        conditionParmMap.put("", "value");

        Query query = CustomHibernateUtils.getParmQueryObject(conditionParmMap, <POJO_NAME>.class);
        List ubList = query.list();
        for (Object obj : ubList) {
            System.out.println("UbdId-------------" + ((<POJO_NAME>) obj).getUbdId());

        }
        HibernateUtil.closeSession();

    }


3. Retrieving data from one to many relationship table.

    public void mappingTableDataRetrievalWithConditions() {

        Map<String, Object> conditionParmMap = new HashMap<String, Object>();
       conditionParmMap.put("", "value");

        Query query = CustomHibernateUtils.getParmQueryObject(conditionParmMap, <POJO_NAME>.class);
        List<<POJO_NAME>> objectList = query.list();

        for (<POJO_NAME> businessObject : objectList) {

            Set objectSet = businessObject.getObjectSet();
            Object[] arr = objectSet.toArray();
            for (Object object : arr) {
                System.out.println("value------------------->" + ((POJO_NAME_TWO) object).getxxxxxxx());
            }

        }
        HibernateUtil.closeSession();

    }


4. Joining Two Tables Table A- POJO_ONE, Table B -POJO_TWO

 public void joinTwoTablesAndDataRetrieval() {

        Map<String, Object> conditionParmMap = new HashMap<String, Object>();
  	conditionParmMap.put("JOINING_TABLE_REPRESANTATION_FIELD_IN_POJO_ONE.<FIELD_NAME>",BigDecimal.valueOf(27));

        String[] tableAndJoinColum = {"<POJO_ONE>", "JOINING_TABLE_REPRESANTATION_FIELD_IN_POJO_ONE"};

        Query query = CustomHibernateUtils.getJoinQueryObject(conditionParmMap, tableAndJoinColum);
        List objectList = query.list();

        Iterator ite = objectList.iterator();
        while (ite.hasNext()) {
            Object[] objects = (Object[]) ite.next();
            <POJO_ONE> pojoOneObject = (<POJO_ONE>) objects[0];
            <POJO_TWO> pojoTwoObject = (<POJO_TWO>) objects[1];

        }

        HibernateUtil.closeSession();

    }


5. Aggregate Functions Demo

    public void aggregateFunction() {
       private static final String MIN = "min";//This should defined globally

        Map<String, Object> conditionParmMap = new HashMap<String, Object>();
        conditionParmMap.put("", "");
        conditionParmMap.put("", MIN);

        Query query = CustomHibernateUtils.getParmQueryObject(conditionParmMap,  <POJO_NAME>.class);
        List objList = query.list();

        for (Object obj : objList) {
            System.out.println("obj id-------------" + ((BigDecimal) obj));

        }

        HibernateUtil.closeSession();

    }


6.Join Two Tables. POJO_ONE and POJO_TWO. Aggregated Function is there for joining table's field.

  public void joinQueryWithAggregateFunction() {

     private static final String MAX = "max";//This should defined globally
        Map<String, Object> conditionParmMap = new HashMap<String, Object>();
        conditionParmMap.put("status", "1");
        conditionParmMap.put("<POJO_TWO_REPRESENTATION_IN_POJO_ONE>.<FIELD_NAME>", MAX);

        String[] tableAndJoinColum = {"<POJO_ONE>", "<POJO_TWO_REPRESENTATION_IN_POJO_ONE>"};

        Query query = CustomHibernateUtils.getJoinQueryObject(conditionParmMap, tableAndJoinColum);
        List objList = query.list();

        for (Object obj : objList) {
            System.out.println("obj Id-------------" + ((BigDecimal) obj));

        }

        HibernateUtil.closeSession();

    }

Advertisements
Tagged with: , ,
Posted in Uncategorized
One comment on “Flexible Utilities for Data Retrieval in Hibernate
  1. thrisha says:

    This article was very helpful for me.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: