Java - HIBERNATE
description
Transcript of Java - HIBERNATE
Przygotowali: Łukasz Monkiewicz, Przygotowali: Łukasz Monkiewicz, Łukasz ZawadzkiŁukasz Zawadzki
Java-
HIBERNATE
Plan prezentacjiPlan prezentacji
► Co to jest Hibernate??Co to jest Hibernate??► Podstawowe cechy HibernatePodstawowe cechy Hibernate►Dlaczego Hibernate jest wartościową Dlaczego Hibernate jest wartościową
technologią??technologią??► Podstawowe elementy rozwijanej aplikacjiPodstawowe elementy rozwijanej aplikacji►Użycie złożonych relacji i zapytań, Użycie złożonych relacji i zapytań,
kryteriów, dziedziczeniakryteriów, dziedziczenia► XDoclet a HIBERNATEXDoclet a HIBERNATE► Porównanie do EJBPorównanie do EJB
Co to jest hibernate??Co to jest hibernate??
► Jest to technologia wysokiej wydajności i Jest to technologia wysokiej wydajności i szybkości działania służąca do szybkości działania służąca do wykonywania operacji na obiektowo – wykonywania operacji na obiektowo – relacyjnych bazach danych z poziomu relacyjnych bazach danych z poziomu języka Javajęzyka Java
Podstawowe cechy technologii Podstawowe cechy technologii Hibernate:Hibernate:
►Nie ma potrzeby implementowania Nie ma potrzeby implementowania interfejsówinterfejsów
►Dowolna klasa może być klasą Dowolna klasa może być klasą reprezentującą encjęreprezentującą encję
►Wygodne i intuicyjne mapowanie plików Wygodne i intuicyjne mapowanie plików struktury xml na klasystruktury xml na klasy
►Mniej kodu = mniej błędówMniej kodu = mniej błędów►Optymalna wydajnośćOptymalna wydajność
Dlaczego warto nauczyć się Dlaczego warto nauczyć się HibernateHibernate
► Proste zasady działania Proste zasady działania ►Możliwość korzystania z możliwości SQL Możliwość korzystania z możliwości SQL
bez wychodzenia poza granicę języka Javabez wychodzenia poza granicę języka Java►Możliwość stworzenia dużej bazy bez Możliwość stworzenia dużej bazy bez
większego wkładu pracywiększego wkładu pracy►Open sourceOpen source►Dostepność narzędzi open sourceDostepność narzędzi open source► PopularnośćPopularność
Podstawowe elementy Podstawowe elementy Aplikacji Aplikacji
► Klasa reprezentująca encję:Klasa reprezentująca encję:1.1. Posiada metody get i set dla atrybutów klasy – Posiada metody get i set dla atrybutów klasy –
pól w tabeli:pól w tabeli:
Class EntityClass Entity{{
int id;int id;
private void setId(int id)private void setId(int id){{
this.id = id;this.id = id;}}
public int getId()public int getId(){{
return id;return id;}}
}}
Podstawowe elementy Aplikacji Podstawowe elementy Aplikacji c.d. c.d.
1.1. Posiada bez argumentowy konstruktor.Posiada bez argumentowy konstruktor.► Plik mapowania(Entity.hbm.xml):Plik mapowania(Entity.hbm.xml):<hibernate-mapping> <hibernate-mapping>
<class name="Entity" table=„Entity"> <class name="Entity" table=„Entity">
<id name="id" column="ID"> <id name="id" column="ID">
<generator class="increment"/> <generator class="increment"/>
</id> </id>
<property name="date" type="timestamp" column="DATE"/><property name="date" type="timestamp" column="DATE"/>
<property name="title"/> <property name="title"/>
</class> </class>
</hibernate-mapping> </hibernate-mapping>
Podstawowe elementy Aplikacji Podstawowe elementy Aplikacji c.d. c.d.
► Plik konfiguracji (hibernate.properties lub Plik konfiguracji (hibernate.properties lub hibernate.cfg.xml) :hibernate.cfg.xml) :
<hibernate-configuration> <session-factory>
<!-- Database connection settings --> <property name="connection.driver_class">
org.hsqldb.jdbcDriver</property> <property name="connection.url">
jdbc:hsqldb:data/tutorial</property> <property name="connection.username">
sa</property> <property name="connection.password"></property> <property name="dialect">org.hibernate.dialect.HSQLDialect</property> <property name="show_sql">
true</property>
<mapping resource="Entity.hbm.xml"/> </session-factory>
</hibernate-configuration>
Podstawowe elementy Aplikacji Podstawowe elementy Aplikacji c.d. c.d.
► PrzykładowyPrzykładowy kod wykonywalny:kod wykonywalny:
class EntityManagerclass EntityManager
{{
public static void main(String[] args)public static void main(String[] args)
{{
EntityManager em = new EntityMenager();EntityManager em = new EntityMenager();
em.createAndStoreSomething(„nazwa”, new Date());em.createAndStoreSomething(„nazwa”, new Date());
}}
} }
Podstawowe elementy Aplikacji Podstawowe elementy Aplikacji c.d. c.d.
► PrzykładowyPrzykładowy kod wykonywalny:kod wykonywalny:
public void createAndStoreSomething(String title, new Date()) {public void createAndStoreSomething(String title, new Date()) {public static final SessionFactory sessionFactory = new public static final SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Configuration().configure().buildSessionFactory(); public static final ThreadLocal session = new ThreadLocal(); public static final ThreadLocal session = new ThreadLocal(); Session s = (Session) session.get(); Session s = (Session) session.get(); if( s == null) {if( s == null) {
s = sessionFactory.openSession(); s = sessionFactory.openSession(); session.set(s); session.set(s);
}}Transaction tx = s.beginTransaction(); Transaction tx = s.beginTransaction(); Entity ent = new Entity();Entity ent = new Entity();ent.setTitle(title); ent.setTitle(title); ent.setDate(theDate); ent.setDate(theDate); s.save(theEvent);s.save(theEvent);tx.commit(); tx.commit(); s.close();s.close();session.set(null);session.set(null);
}}
Podstawowe elementy Aplikacji Podstawowe elementy Aplikacji c.d. c.d.
► Przedstawienie relacji między tabelami:Przedstawienie relacji między tabelami:
_________________ __________________________________ _________________
| PERSON | | Entity || PERSON | | Entity |
|_______________ | | _______________ ||_______________ | | _______________ |
| person_id | * 0..1| ID || person_id | * 0..1| ID |
| name | ----------------------------------| title || name | ----------------------------------| title |
| | | date | | | | date |
| | | || | | |
| | | || | | |
|_______________ | |________________||_______________ | |________________|
Podstawowe elementy Aplikacji Podstawowe elementy Aplikacji c.d. c.d.
► Klasa Person.javaKlasa Person.java
class Person {class Person {
int person_id;int person_id;
String name;String name;
Entity ent;Entity ent;
//metody get i set dla atrybutów…//metody get i set dla atrybutów…
public Entity getEntity() {public Entity getEntity() {
return ent;return ent;
}}
public void setEntity(Entity ent) {public void setEntity(Entity ent) {
this.ent = ent;this.ent = ent;
}}
}}
Podstawowe elementy Aplikacji Podstawowe elementy Aplikacji c.d. c.d.
► Person.hbm.xml :Person.hbm.xml :
<hibernate-mapping> <hibernate-mapping>
<class name=„Person" table=„Persons"> <class name=„Person" table=„Persons">
<id name=„person_id" column=„PERSON_ID"> <id name=„person_id" column=„PERSON_ID">
<generator class="increment"/> <generator class="increment"/>
</id> </id>
<property name=„name”/><property name=„name”/> <many-to-one
name=„ent„ column="ID"class=„Entity„ not-null="true"/>
</class> </class>
</hibernate-mapping></hibernate-mapping>
Podstawowe elementy Aplikacji Podstawowe elementy Aplikacji c.d. c.d.
► Klasa Entity.java :Klasa Entity.java :
class Entity {class Entity {private Set persons = new HashSet();……
public void setPersons(Set persons) {
this.persons = persons;}public Set getPersons() {
return persons;}
}
Podstawowe elementy Aplikacji Podstawowe elementy Aplikacji c.d. c.d.
► Entity.hbm.xml :Entity.hbm.xml :
<hibernate-mapping> <hibernate-mapping> <class name="Entity" table=„Entity"> <class name="Entity" table=„Entity">
……
<set name=„persons"><key column=„ID"/><one-to-many class=„Person"/>
</set>
</class> </class> </hibernate-mapping> </hibernate-mapping>
Podstawowe elementy Aplikacji Podstawowe elementy Aplikacji c.d. c.d.
► Przykładowy kod wykorzystujący relację:Przykładowy kod wykorzystujący relację:
class EntityManagerclass EntityManager{{
public static void main(String[] args) {public static void main(String[] args) {public static final SessionFactory sessionFactory = new public static final SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory(); Configuration().configure().buildSessionFactory(); public static final ThreadLocal session = new ThreadLocal(); public static final ThreadLocal session = new ThreadLocal(); Session s = (Session) session.get(); Session s = (Session) session.get(); if( s == null) {if( s == null) { s = sessionFactory.openSession(); s = sessionFactory.openSession();
session.set(s); session.set(s); }}Transaction tx = s.beginTransaction(); Transaction tx = s.beginTransaction(); Person aPerson = (Person) session.load(Person.class, 2); Person aPerson = (Person) session.load(Person.class, 2); Entity anEntity = (Entity) session.load(Event.class, 1); Entity anEntity = (Entity) session.load(Event.class, 1); anEntity.getPersons().add(aPerson);anEntity.getPersons().add(aPerson);tx.commit();tx.commit();s.close();s.close();session.set(null); session.set(null);
}}}}
Złożone zapytaniaList mothers = session.createQuery(List mothers = session.createQuery(
"select mother from Cat as cat join cat.mother as mother where cat.name "select mother from Cat as cat join cat.mother as mother where cat.name = ?")= ?")
.setString(0, name).setString(0, name)
.list();.list();
List kittens = session.createQuery(List kittens = session.createQuery(
"from Cat as cat where cat.mother = ?")"from Cat as cat where cat.mother = ?")
.setEntity(0, pk).setEntity(0, pk)
.list();.list();
Cat mother = (Cat) session.createQuery(Cat mother = (Cat) session.createQuery(
"select cat.mother from Cat as cat where cat = ?")"select cat.mother from Cat as cat where cat = ?")
.setEntity(0, izi).setEntity(0, izi)
.uniqueResult();.uniqueResult();
Kryteria
List cats = sess.createCriteria(Cat.class)List cats = sess.createCriteria(Cat.class)
.add( Restrictions.like("name", "Fritz%") ).add( Restrictions.like("name", "Fritz%") )
.add( Restrictions.or(.add( Restrictions.or(
Restrictions.eq( "age", new Integer(0) ),Restrictions.eq( "age", new Integer(0) ),
Restrictions.isNull("age")Restrictions.isNull("age")
) )) )
.list();.list();
List cats = sess.createCriteria(Cat.class)List cats = sess.createCriteria(Cat.class)
.add( Restrictions.sql(.add( Restrictions.sql(
"lower({alias}.name) like lower(?)", "Fritz%", Hibernate.STRING"lower({alias}.name) like lower(?)", "Fritz%", Hibernate.STRING
) )) )
.list();.list();
Dziedziczenie
public class Person {public class Person {String name;String name;Long id;Long id;
... // getter, setter ... // getter, setter }}public class Employee extends Person {public class Employee extends Person {
String NIP;String NIP;... // getter, setter... // getter, setter
}}
Dziedziczenie
<class name="Person" table="persons" <class name="Person" table="persons" discriminator-value="P"discriminator-value="P">>
<id name="id"><id name="id">
<generator class="native"/><generator class="native"/>
</id></id>
<discriminator column="subclass" type="character"/><discriminator column="subclass" type="character"/>
<property name="name" type="string"/><property name="name" type="string"/>
<subclass name="Employee" discriminator-value=„<subclass name="Employee" discriminator-value=„EE">">
<property name="NIP" type="string"/><property name="NIP" type="string"/>
</subclass></subclass>
</class></class>
Relacje: wiele do wiele<class name="Person"><class name="Person">
<id name="id" column="personId"><id name="id" column="personId">
<generator class="native"/><generator class="native"/>
</id></id>
<set name="addresses"><set name="addresses">
<key column="personId"/><key column="personId"/>
<many-to-many column="addressId" class="Address"/><many-to-many column="addressId" class="Address"/>
</set></set>
</class></class>
<class name="Address"><class name="Address">
<id name="id" column="addressId"><id name="id" column="addressId">
<generator class="native"/><generator class="native"/>
</id></id>
<set name="people" inverse="true"><set name="people" inverse="true">
<key column="addressId"/><key column="addressId"/>
<many-to-many column="personId" class="Person"/><many-to-many column="personId" class="Person"/>
</set></set>
</class></class>
XDoclet i Hibernate/**/**
* @hibernate.class* @hibernate.class
* table="Person"* table="Person"
*/*/
public class Person {public class Person {
private Long id;private Long id;
private String name;private String name;
/*/*
* @hibernate.id* @hibernate.id
* generator-class="native"* generator-class="native"
* column="PERSON_ID"* column="PERSON_ID"
*/*/
public Long getId() { return id;}public Long getId() { return id;}
private void setId(Long id) { this.id=id;}private void setId(Long id) { this.id=id;}
/*/*
* @hibernate.* @hibernate.propertyproperty
* column="NAME"* column="NAME"
*/*/
public String getName() { return id;}public String getName() { return id;}
private void setName(Name name) { this.name=name;}private void setName(Name name) { this.name=name;}
}}
Porównanie do EJB
►Mniej zbędnego koduMniej zbędnego kodu►Nie wymaga serwera aplikacjiNie wymaga serwera aplikacji►WydajnośćWydajność►Rozbudowany język zapytańRozbudowany język zapytań
Podsumowanie Podsumowanie ► Technologia popularna ( ok. 1500 pobrań dziennie )Technologia popularna ( ok. 1500 pobrań dziennie )► Prosta implementacja a efekt działania aplikacjiProsta implementacja a efekt działania aplikacji► Więcej na Więcej na www.hibernate.orgwww.hibernate.org► Literatura: „Hibernate in action” – wyd. ManningLiteratura: „Hibernate in action” – wyd. Manning