Documente Academic
Documente Profesional
Documente Cultură
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.
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.
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.
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
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(); }
session.beginTransaction();
Event theEvent = new Event(); theEvent.setTitle(title); theEvent.setDate(theDate);
session.save(theEvent);
session.getTransaction().commit(); } }
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
Questions