Sunteți pe pagina 1din 19

HIBERNATE An Introduction

Arun Srec

What is Hibernate?
It is an object-relational mapping (ORM) solution for Java We make our data persistent by storing it in a database Hibernate takes care of this for us

Object-Relational Mapping
It is a programming technique for converting object-type data of an object oriented programming language into database tables. Hibernate is used convert object data in JAVA to relational database tables.

Why Hibernate and not JDBC?

JDBC maps Java classes to database tables (and from Java data types to SQL data types)
Hibernate automatically generates the SQL queries. Hibernate provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.

Makes an application portable to all SQL databases.

Hibernate vs. JDBC (an example)

JDBC tuple insertion st.executeUpdate(INSERT INTO book VALUES(Harry Potter,J.K.Rowling));


Hibernate tuple insertion session.save(book1);

Architecture

Hibernate sits between your code and the database Maps persistent objects to tables in the database

Example Application
Consider an application that can store events we want to attend, and information about the hosts of these events. In this example we use MySQL database.

The first persistent class Event.java


package events; import java.util.*; public class Event { private Long id; private String title; private Date date; public Event() {} public Long getId() { return id; }

public Date getDate() { return date; }


public void setDate(Date date) { this.date = date; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }

private void setId(Long id) { this.id = id; //unique identifier }

The Mapping file - Event.hbm.xml


<hibernate-mapping> <class name="events.Event" table="EVENTS"> <id name="id" column="EVENT_ID"> <generator class="native"/> </id> <property name="date" type="timestamp column="EVENT_DATE"/> <property name="title"/> </class> </hibernate-mapping>
By default, property name column name. But date is a reserved keyword in most databases. Hence, provide a different name.

Hibernate Configuration file hibernate.cfg.xml


<?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">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://localhost/event_database</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> . <mapping resource="events/Event.hbm.xml"/> </session-factory> </hibernate-configuration>

Session (org.hibernate.Session)
A

short-lived object Representing a conversation between the application and the database Wraps a JDBC connection Factory for Transaction

SessionFactory (org.hibernate.SessionFactory)
A

cache of compiled mappings for a single database A factory for Session

HibernateUtil.java
package util; import org.hibernate.*; import org.hibernate.cfg.*; 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); } } public static SessionFactory getSessionFactory() { return sessionFactory; } } Provides startup and easy use of SessionFactory.

EventManager.java
package events; import org.hibernate.Session; import java.lang.*; import java.util.Date; import util.HibernateUtil; public class EventManager { public static void main(String[] args) { EventManager mgr = new EventManager(); if (args[0].equals("store")) { mgr.createAndStoreEvent("My Event", new Date()); } HibernateUtil.getSessionFactory().close(); }

private void createAndStoreEvent(String title, Date theDate) { Session session = HibernateUtil.getSessionFactory().getCurrentSession();

session.beginTransaction();
Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate);

session.save(theEvent);
session.getTransaction().commit(); } }

Building with Ant build.xml

Apache Ant is a software tool for automating software build processes. The build.xml file will tell Ant to add all files in the lib directory ending with .jar to the classpath used for compilation. It will also copy all non-Java source files to the target directory, e.g. configuration and Hibernate mapping files.

Run!
>ant run Daction=store

Sources and References


www.hibernate.org www.ant.apache.org www.slf4j.org/dist/ (Find the missing .jar file here)

Questions

S-ar putea să vă placă și