Hibernate Framework : ORM Tool :: Introduction
- What is Hibernate?
- What is O/R Mapping.
- Type of ORM available
- Architecture of Hibernate
- Features of Hibernate
- Why Hibernate?
- How it is Different from JDBC Styles
- Instance States
- Versions of Hibernate Framework.
- How Hibernate Works
- Working With Hibernate
- How to Work with Hibernate using MyEclipse. { Sample Example }
- Download Examples
What is Hibernate? |
Hibernate Framework
- Hibernate is the ORM ( Object Relationship Mapping ) Framework or Tool.
- Hibernate is an open source framework implemented by JBoss, Inc. (now part of Red Hat)
- Hibernate is a persistence framework which will automate and simplify the persistence operations with the relational databases.
- Hibernate framework is implemented on the top of JDBC technology. I.e. Hibernate internally uses JDBC technology for the Database interactions.
- Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database.
- Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.
- Hibernate is free software that is distributed under the GNU Lesser General Public License.
- Hibernate’s primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types).
- Hibernate also provides data query and retrieval facilities.
- Hibernate generates the SQL calls and attempts to relieve the developer from manual result set handling and object conversion and keep the application portable to all supported SQL databases with little performance overhead.
What is O/R Mapping |
- Mapping Java classes to database tables is accomplished through the configuration of an XML file or by using Java Annotations.
- When using an XML file, Hibernate can generate skeletal source code for the persistence classes.
Type of ORM available |
Type of ORM tools Available
- JDBC
- EJB2 [Entity Bean]
- EJB3 [JPA] *
- Hibernate*
- IBaties*
- TopLink*
- JDO*
Note :- (*) Means ORM Tool and Hibernate is more popular and best among all other ORM tools
Architecture of Hibernate |
A (very) high-level view of the Hibernate architecture
- SessionFactoryA threadsafe cache of compiled mappings for a single database. A factory for Session and a client of ConnectionProvider.
- SessionA single-threaded, short-lived object representing a conversation between the application and the persistent store.
- Persistent objects and collectionsShort-lived, single threaded objects containing persistent state and business function.
- Transient and detached objects and collections Instances of persistent classes that are not currently associated with a Session.
- TransactionA single-threaded, short-lived object used by the application to specify atomic units of work.
- ConnectionProviderA factory for (and pool of) JDBC connections. Abstracts application from underlying Datasource or DriverManager.
- TransactionFactoryA factory for Transaction instances. Not exposed to the application, but can be extended/implemented by the developer.
- Extension InterfacesHibernate offers many optional extension interfaces you can implement to customize the behavior of your persistence layer.
Hibernate Architecture
Features of Hibernate |
- AS a ORM tool Hibernate will do the persistence work transparently.
- Hibernate generate the JDBC code.
- Hibernate generates the required SQL queries which are well tuned by the persistence experts.
- Hibernate is responsible to take the resources like Connection, Statement, ResultSet and Hibernate is responsible to clean all type of resouces properly after use.
- Hibernate provides various types of mapping techniques to persist simple java objects, collections, inherited Objects etc.
- Hibernate provides different Transaction Models like JDBC Transactions, JTA Transactions.
- Hibernate provide powerful query language like HQL, QBC, QBE etc.
Why Hibernate |
- Runtime performance monitoring.
- Eclipse support.
- Hibernate is Free under LGPL
- Minimizes Code
- Hibernate is Scalable
- Does not require a container
- Less Development.
- Automatic Key Generation.
- JDK 1.5 Enhancements
- EJB3-style persistence operations
- Hibernate XML binding enables data to be represented as XML and POJOs interchangeably.
- The EJB3 draft specification support for POJO persistence and annotations.
- Retains natural object model (transparent)
- Model is not tied to persistence implementation
- Enhanced Criteria query API.
Different from JDBC Styles |
When we develop persistence logic for our application with JDBC technology, we need to do the following steps
- Take the Connection
- Create the Statement
- Prepare the SQL Query
- Submit the query to DB engine
- Process the results
- Cleanup the resource
- Handling Exceptions
Which leads
- Creating Problem in Code Duplication.
- Creating Problem in Performance if not tuned properly.
Java Connecting Database through JDBC Style
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException e)
{
System.out.println("could not load MySQL Driver")
}
try
{
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/javaskoolDB","root","admin");
Statement st=con.createStatement();
String query="Select * from user where uid=\'"+user.getUserId()+"\'";
ResultSet rs=st.executeQuery(query);
.....
Java Connecting Database using Hibernate Style
Instance states |
An instance of a persistent classes may be in one of three different states, which are defined with respect to a persistence context. The Hibernate Session object in the persistence context.
Versions of Hibernate Framework |
- Hibernate was started in 2001 by Gavin King as an alternative to using EJB2-style entity beans. Its mission back then was to simply offer better persistence capabilities than offered by EJB2 by simplifying the complexities and allowing for missing features.
- Early in 2003, the Hibernate development team began Hibernate2 releases which offered many significant improvements over the first release.
- JBoss, Inc. (now part of Red Hat) later hired the lead Hibernate developers and worked with them in supporting Hibernate.
- As of 2010 the current version of Hibernate is Version 3.x.
- This version introduced new features like a new Interceptor/Callback architecture, user defined filters, and JDK 5.0 Annotations (Java’s metadata feature).
- As of 2010 Hibernate 3 (version 3.5.0 and up) is a certified implementation of the Java Persistence API 2.0
How Hibernate Works |
- Don’t need to change the way your objects behave.
- Don’t need to implement any magical interface
- Create XML “mapping document” telling hibernate the classes
- We use an database (MySQL), so we have to install MySQL database server.
Working With Hibernate |
First, we create a class that represents the Customer that we want to store in database.
1. The first POJO class
Our first persistent class is a simple JavaBean class with some properties
- You can see that this class uses standard JavaBean naming conventions for property getter and setter methods, as well as private visibility for the fields.
- This is a recommended design – but not required.
- Hibernate can also access fields directly, the benefit of accessor methods is robustness for refactoring.
- The no-argument constructor is required to instantiate an object of this class through reflection.
- The no-argument constructor is a requirement for all persistent classes; Hibernate has to create objects for you, using Java Reflection.
In the next step, we tell Hibernate about this persistent class.
2. The mapping file
- Hibernate needs to know how to load and store objects of the persistent class.
- This is where the Hibernate mapping file comes into play.
- The mapping file tells Hibernate what table in the database it has to access, and what columns in that table it should use.
The basic structure of a mapping file looks like this:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
[...]
</hibernate-mapping>
Example
We continue with the main configuration of Hibernate.
3. Hibernate configuration
- We now have a persistent class and its mapping file in place. It is time to configure Hibernate. Before we do this, we will need a database. MySQL.
- Hibernate is the layer in your application which connects to this database, so it needs connection information.
- The connections are made through a JDBC connection pool, which we also have to configure.
- The Hibernate distribution contains several open source JDBC connection pooling tools.
- For Hibernate’s configuration, we can use a simple hibernate.properties file, a slightly more sophisticated hibernate.cfg.xml file, or even complete programmatic setup.
- Most users prefer the XML configuration file
4. Loading and storing objects
Finally, we can use Hibernate to load and store objects. We write an CustomerClient class with a main() method.
- We create a new Customer object, and hand it over to Hibernate. Hibernate now takes care of the SQL and executes INSERTs on the database. Let’s have a look at the Session and Transaction-handling code before we run this.
- A Session is a single unit of work. For now we’ll keep things simple and assume a one-to-one granularity between a Hibernate Session and a database transaction. To shield our code from the actual underlying transaction system (in this case plain JDBC, but it could also run with JTA) we use the Transaction API that is available on the Hibernate Session.
- What does sessionFactory.getCurrentSession() do? First, you can call it as many times and anywhere you like, once you get hold of your SessionFactory (easy thanks to HibernateUtil). The getCurrentSession() method always returns the "current" unit of work. Remember that we switched the configuration option for this mechanism to "thread" in hibernate.cfg.xml? Hence, the current unit of work is bound to the current Java thread that executes our application. However, this is not the full picture, you also have to consider scope, when a unit of work begins and when it ends.
- A Session begins when it is first needed, when the first call to getCurrentSession() is made. It is then bound by Hibernate to the current thread. When the transaction ends, either through commit or rollback, Hibernate automatically unbinds the Session from the thread and closes it for you. If you call getCurrentSession() again, you get a new Session and can start a new unit of work. This thread-bound programming model is the most popular way of using Hibernate, as it allows flexible layering of your code (transaction demarcation code can be separated from data access code, we’ll do this later in this tutorial).
- Related to the unit of work scope, should the Hibernate Session be used to execute one or several database operations? The above example uses one Session for one operation. This is pure coincidence, the example is just not complex enough to show any other approach. The scope of a Hibernate Session is flexible but you should never design your application to use a new Hibernate Session for every database operation. So even if you see it a few more times in the following (very trivial) examples, consider session-per-operation an anti-pattern. A real (web) application is shown later in this tutorial.
Check the Database table whether record is saved.
How to Work with Hibernate |
Steps involved to work with Hibernate using MyEclipse
Click Here to Download the MySQL Connector
Click Here to Download the MySQL Connector
Click Below to download the Examples
You have made some really good points there. I looked on the web for additional information about the issue and found most individuals will go along with your views on this web site.
Well, your blog is quite interesting and helpful. I just loved reading your blog.
Wonderful points you have mentioned here, Thank you for sharing.
My brother recommended I might like this web site. He was once totally
right. This put up truly made my day. You can not
imagine just how so much time I had spent for this information!
Thanks!