Sie sind auf Seite 1von 25

HIBERNATE

Qu es un ORM (1/3) (Object relational Mapping)


Problemas al trabajar con POO + BBDD Relacionales R l i l Dos paradigmas muy diferentes
Objetos, atributos, asociaciones con otros Obj t t ib t i i t objetos, herencia, UML Columnas, claves ajenas, consultas lenguaje SQL

Q Qu es un ORM (2/3) ( )

JavaObject
int id; String name; String getName() int getId() void setName(String) void setId(int) ( )

SQL Table
id [int] primary key, key name [varchar(50)]

La funcin de un O/R Mapper tiene lugar aqu

Qu es un ORM (3/3)
Garantizar persistencia d objetos: G ti i t i de bj t necesario conexin JDBC + consultas SQL para cada propiedad de estos objetos Si los objetos son grandes muy costoso Problema llamado diferencia objetorelacional

Qu es Hibernate (1/2)
Mapeador objeto-relacional (ORM) Uno de los mejores Cdigo abierto Popular (13000 descargas/mes)

Qu es Hibernate (2/2)
API personalizada Persistencia para JavaBeans HQL: Hibernate Query Language

Por qu Hibernate (1/2)


Transparente (trabajamos con el modelo) Poco cdigo No requiere contenedor Modelo e implementacin independientes

Por qu Hibernate (2/2)


Permite grandes consultas (HQL y/ SQL) Optimiza el acceso a los datos

Objetivos de Hibernate (1/1)


Ventajas de las BBDD Relacionales j usando el lenguaje de POO Desaparecer el 95% de los problemas de persistencia de datos Reducir el trabajo

Ejemplo sencillo (1/2)


Aplicacin destinada a reportero TV Almacenar eventos y patrocinadores de stos t Primero descargamos Hibernate y situamos sit amos los .jar en el directorio lib jar

Ejemplo sencillo (2/2)


+lib cglib2.jar commons-logging.jar hibernate2.jar jta.jar odmg.jar commons-collections.jar dom4j.jar j jdbc2_0-stdext.jar _ j log4j.jar

La primera clase (1/2)


Clase Java que describe la aplicacin antes p presentada. Nombre: Event.java j
package de.gloegl.road2hibernate; public class Event { private String title; private Date date; private Long id; public Long getId() { return id; } private void setId(Long id) { this.id = 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; }

La primera clase (2/2)


setId privado; identificador nico que slo usar Hibernate id tipo Long verdadero (no tipo primitivo)
+lib lib <hibernate jars> +src +de d +gloegl +road2hibernate Event.java E tj

El fichero de mapeo (1/4)


Dice a Hibernate cmo persistir la clase Java Nombre: Event.hbm.xml N b E t hb l (e uest o (en nuestro caso)

El fichero de mapeo (2/4)


<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC hibernate mapping "-//hibernate/hibernate Mapping DTD 2.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd"> <hibernate-mapping> <class name="de.gloegl.road2hibernate.Event" table="EVENTS"> <id name="id" column="uid" type="long"> name id column uid type long > <generator class="increment"/> </id> <property name="date" type="timestamp"/> p p y yp p <property name="title" column="eventtitle"/> </class> </hibernate-mapping> pp g

El fichero de mapeo (3/4)


Persiste la clase Event dentro de la tabla EVENTS Identificador nico Id tifi d i y cmo aumentarlo t l Properties atributos de clase type y column valores por defecto

El fichero de mapeo (4/4)


+lib lib <hibernate jars> +src +de +gloegl +road2hibernate Event.java Event.hbm.xml

Siguientes pasos (1/1)


Obtener una BBDD (MySQL, HSQLDB ) Configurar Hibernate para esa BBDD con un XML? Arrancar Hibernate

Java arranca Hibernate (1/2)


package de.gloegl.road2hibernate; k d l l d2hib t import net.sf.hibernate.SessionFactory; import net.sf.hibernate.HibernateException; import net.sf.hibernate.cfg.Configuration; p g g ; public class EventManager { private SessionFactory sessionFactory; public EventManager() { try { System.out.println("Initializing Hibernate"); sessionFactory = new Configuration().configure().buildSessionFactory(); y g () g () y(); System.out.println("Finished Initializing Hibernate"); } catch (HibernateException e) { e.printStackTrace(); } } public static void main(String[] args) { EventManager instance = new EventManager(); System.exit(0); } }

Java arranca Hibernate (2/2)


+lib <hibernate jars> +src +de d +gloegl +road2hibernate Event.java Event.hbm.xml EventManager.java g j +data build.bat

HQL (1/3)
SQL orientado a objetos i t d bj t
Clases y atributos vs. Tablas y columnas Asociaciones, polimorfismo

Soporta operaciones relacionales


Proyeccin, agregacin, Proyeccin agregacin grupos Subconsultas Funciones SQL F i

HQL (2/3)
Consulta ms simple
from AuctionItem Selecciona todos los AuctionItems

Otra ms complicada
select item from AuctionItem item join item.bids bid where item.description like program% h it d i ti lik % and bid.amount > 100 Selecciona todos los AcutionItems con un atributo bid > 100 y una descripcin que empiece por program

HQL (3/3)
Proyeccin
select item description bid amount item.description, bid.amount from AuctionItem item j join item.bids bid where bid.amount > 100 order by bid.amount desc Obtiene la descripcin y la cantidad de todos los AuctionItems con un atributo bid > 100

Bibliografa
http://www.hibernate.org http://www.programacion.com/java/tutorial/ hibernate hib t

Herramientas de apoyo
http://xdoclet.sf.net http://boss.bekk.no/boss/middlegen http://www.andromda.org http://www andromda org

Das könnte Ihnen auch gefallen