Hibernate Introduction
Please read a discussion on ORM, before going further at Introduction To ORM.Hibernate is an ORM framework. It provides capability to interact with database in an object oriented way. Hibernate provides its own HQL (Hibernate query language) also. The concepts of ORM are now adopted in EJB3.0 in the form of entity beans and Jave Persistence API (JPA). Hibernate supports Entity beans also. This means hibernate can act as an implementation provider for Entity beans. In fact, JBoss uses hibernate as implementation provider for Entity beans. Hibernate has its own set of API's also which at the moment are richer than JPA. Going forward however we might see Entity beans and JPA closing this gap.
Let's make a Java project where we will persist the data into the database. First download the Hibernate Core from download site
- doc - contains the reference document for hibernate
- eg - example application
- etc - configuration files
- grammer
- lib - contains dependencies for hibernate. See lib/_README.txt for details about libraries.
- src - source code of hibernate
- test - test suite
- hibernate3.jar - hibernate library
Make a simple Java application in your IDE. Have the following libraries in the build path:
From Hibernate Core (<hibernate-distribution-*>/lib/required)
- antlr-2.7.6
- commons-collections-3.1.jar
- dom4j-1.6.1.jar
- javassist-3.9.0.GA.jar
- jta-1.1.jar
- slf4j-api-1.5.8.jar
- <hibernate-distribution-*>/lib/ -Choose between cglib or javassist
- <hibernate-distribution>/*hibernate3.jar
Download slf4j from http://www.slf4j.org/dist/
- slf4j-simple-1.5.8.jar
- hsqldb.jar - We will be using hypersonic database for this example. you need to download hypersonic jar. For details see Hypersonic.
Hibernate is a Object relational mapping framework. What it will help us is in saving the objects into the relational world. So let's have our Java class whose object instances at runtime will be saved by hibernate to the database.
public class Student { //Id will correspond the primary key in the database private Long id; protected 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;} }
Now we have the domain class definition with us. Now we will put a mapping file which will map this class to the data model in the database. We are not creating the table in the database as we will use hibernate to generate the data model. Though in real life application you would have your data model already created and placed in the database.
Student.hbm.xml (Put it together with Student class)
<?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> <!-- class attributes - name - Java class name table - Table to which this class is mapped schema - The schema where it sits id - name - name of property on Java class. It will result in getId() and setId method column - column in table to which it is mapped generator- how the id's to be generated --> <class name="com.oyejava.Student" table="Student" schema="PUBLIC"> <id name="id" column="STUDENT_ID"> <generator class="increment"/> </id> <!-- name - name of property in Java class. getName() and setName() column - column in table to which it is mapped. --> <property name="name" column="NAME" /> </class> </hibernate-mapping>
Now we will provide hibernate the details to connect to the database. Similar to JDBC coding, the connection details and drivers need to be provided to Hibernate. This is done in a XML file.
hibernate.cfg.xml (Put it in the class path)
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">org.hsqldb.jdbcDriver</property> <property name="connection.url">jdbc:hsqldb:hsql://localhost</property> <property name="connection.username">sa</property> <property name="connection.password"></property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect - This tells the SQL grammer to be used --> <property name="dialect">org.hibernate.dialect.HSQLDialect</property> <!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">thread</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property> <!-- Log out all the sql that hibernate is issuing to datbase. This is very useful for debugging --> <property name="show_sql">true</property> <!-- Create the table looking at class and mapping. Very useful in development Use validate in production environments. --> <property name="hbm2ddl.auto">create</property> <!-- Mapping file. --> <mapping resource="com/oyejava/Student.hbm.xml"/> </session-factory> </hibernate-configuration>
Now we will write a utility class which will start the session factory of hibernate, if it is not started and will return the Session factory. This is the most used pattern of boot strapping Hibernate. Session factory contains all the configuration information at runtime. A Session is retrieve from the Session factory. A session is a light weight object which provide services to interact with database. You can think of Session like JDBC connection, thought it may not open the database connection if not required.
HibernateUtil
public class HibernateUtil { private static SessionFactory sessionFactory; static{ try{ //By default it will look for hibernate.cfg.xml in the class path sessionFactory=new Configuration().configure().buildSessionFactory(); }catch(Throwable ex){ throw new ExceptionInInitializerError(ex); } } public static SessionFactory getSessionFactory(){ return sessionFactory; } public static void shutdown(){ //Close caches and connection pool getSessionFactory().close(); } }
Now let's write the main class in which we will create a Student object and persist it to database
public class HibernateBasic { public static void main(String[] args) { //Get the session from the Session factory Session session = HibernateUtil.getSessionFactory().openSession(); Transaction tx= session.beginTransaction(); Student student = new Student(); student.setName("oyeJava"); Long studentId = (Long)session.save(student); System.out.println(studentId); tx.commit(); session.close(); } }
Run the application and check in the database. It should persist a row of data. Download the source code from down below in the attachment section. The libraries has to be included as per the list given above.
In the above example we saw how to configure hibernate using XML mapping. The present trend is however to move towards annotation based mapping. For annotation based mapping see Hibernate Introduction with Annotation
Back to Hibernate Index Back To Java Home Back To Home
| id | Name | desc | uploaded | Size | Downloads | ||
|---|---|---|---|---|---|---|---|
| 1 | 6 |
|
|
Hibernate Basic | Mon 22 of June, 2009 22:42 IST by lalit | 4.03 Kb | 368 |
Sidebar
Last wiki comments
- AOP: Thanks
- Lalit Bhatt: Superb Collection
- Lalit Bhatt: J2EE training
- Introduction to ORM: timberland shoes
- Introduction to ORM: jordan shoes
- Introduction to ORM: nike air max
- Pune Tourist Spots: KONARK PARK CLOSED
- jQuery Form Validations: Jquery Developer
- Spring Introduction: RG
- SOAP: Re: Assertion
Sidebar
Random Pages
- What markets work on?
- Why projects fail?
- Bharat Band - Jai ho
- The concept of Nation
- Don't hide complexity if it cannot be handled in a robustway
Last blog post comments
-
Bharat Band - Jai ho: How do we protest?
Wed 18 of Aug., 2010 13:13 IST
-
Divided by Destiny: Contact
Fri 23 of July, 2010 16:02 IST
-
Future of Java: thesis writing
Sat 17 of July, 2010 01:50 IST
-
Hang till Death Mr. Kasab: some change
Mon 28 of June, 2010 16:03 IST
-
God Religion : Why we are confused?: Re: Is GOD Necessary?
Tue 15 of June, 2010 17:29 IST
-
God Religion : Why we are confused?: Is GOD Necessary?
Tue 15 of June, 2010 13:06 IST
-
The reason in religion: good
Wed 10 of Mar., 2010 18:30 IST
-
The confusion of Design Patterns: I think at macro level you are right...
Tue 23 of Feb., 2010 03:31 IST
-
The Indian Municipality: Comment
Fri 22 of Jan., 2010 13:20 IST
-
What Government should do?: Re: Review of the Indian Law and Order and Justice Dispensation regime.
Fri 22 of Jan., 2010 13:16 IST
Post new comment