Hibernate
1
1. Wprowadzenie.
2. Uruchomienie dostarczonego przykładu.
3. Własny przykład.
Wprowadzenie
2
Hibernate (http://www.hibernate.org) jest narzędziem realizującym odwzorowanie
obiektów Javy na odpowiednie rekordy w relacyjnej bazie danych.
Hibernate uwalnia programistów od tworzenia większości kodu odpowiedzialnego
za komunikację z bazą danych i pozwala się skupić na logice biznesowej tworzonej
aplikacji. Ponadto biblioteka umożliwia pisanie programów w sposób niezależny od
konkretnej platformy baz danych.
Uruchomienie przykładu
3
●
załadować: http://www.hibernate.org/30.html i rozpakowanie archiwum,
●
umieścić driver JDBC w podkatalogu
lib
,
●
wyedytować plik
etc/hibernate.properties
, i ustawić parametry połączenia
z bazą danych:
...
hibernate.dialect org.hibernate.dialect.MySQLDialect
#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
hibernate.connection.driver_class com.mysql.jdbc.Driver
hibernate.connection.url jdbc:mysql://127.0.0.1/eg
hibernate.connection.username root
hibernate.connection.password
...
Uruchomienie przykładu
4
●
ustawić
hibernate.show_sql=true
w pliku
hibernate.properties
●
z lini komend wewnątrz katalogu
hibernate
wydać polecenie
ant eg
,
●
przejrzeć dane pojawiające się w konsoli,
●
przejrzeć źródła w podkatalogu
eg
.
Własny przykład
5
orders
orders
odr_id
odr_date
contractors
contractors
con_id
con_name
con_address
Struktura przykładu
6
+src
+data
Contractor.java
ContractorManager.java
Contractor.hbm.xml
Order.java
OrderManager.java
Order.hbm.xml
+util
HibernateUtil.java
Example.java
hibermate.cfg.xml
log4j.properties
Contractor.java
7
package data;
import java.util.HashSet;
import java.util.Set;
public class Contractor {
private int id;
private String name;
private String address;
private Set orders = new HashSet();
public Contractor(){
// pusty konstruktor
}
Contractor.java
8
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
Contractor.java
9
public void setAddress(String address) {
this.address = address;
}
public String getAddress() {
return this.address;
}
public void setOrders(Set orders) {
this.orders = orders;
}
public Set getOrders() {
return this.orders;
}
}
Contractor.hbm.xml
10
Pliki
hbm.xml
służą do zdefiniowania odwzorowania relacyjno-obiektowego:
<?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 name="data.Contractor" table="contractors">
<id name="id" column="con_id">
<generator class="native"/>
</id>
Contractor.hbm.xml
11
<property name="name" column="con_name"/>
<property name="address" column="con_address"/>
<set name="orders" inverse="true">
<key column="con_id"/>
<one-to-many class="data.Order"/>
</set>
</class>
</hibernate-mapping>
Order.java
12
...
public class Order {
private int id;
private Date date;
private Contractor contractor;
public Order(){ // pusty konstruktor }
public void setId(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
...
}
Order.hbm.xml
13
...
<hibernate-mapping>
<class name="data.Order" table="orders">
<id name="id" column="odr_id">
<generator class="native"/>
</id>
<property name="date" type="date" column="odr_date"/>
<many-to-one name="contractor" column="con_id"
class="data.Contractor" />
</class>
</hibernate-mapping>
Struktura przykładu
14
+src
+data
Contractor.java
Contractor.hbm.xml
Order.java
Order.hbm.xml
ContractorManager.java
OrderManager.java
+util
HibernateUtil.java
Example.java
hibermate.cfg.xml
log4j.properties
ContractorManager.java
15
Plik
ContractorManager.java
zawiera definicję operacji związanych z obiektem
Contractor
:
...
public class ContractorManager {
public void create(String sName, String sAddress) {
Session session = HibernateUtil.getSessionFactory().
getCurrentSession();
s
ession.beginTransaction();
Contractor c = new Contractor();
c.setName(sName);
c.setAddress(sAddress);
s
ession.save(c);
session.getTransaction().commit();
}
}
ContractorManager.java
16
public Contractor load(int id) {
Session session = HibernateUtil.getSessionFactory().
GetCurrentSession();
session.beginTransaction();
Contractor c = (Contractor) session.load(
Contractor.class, new Integer(id));
session.getTransaction().commit();
return c;
}
}
HibernateUtil.java
17
W pliku
HibernateUtil.java
zawarto kod inicjujący bibliotekę Hibernate.
package util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
HibernateUtil.java
18
static {
try {
// inicjalizacja na podstawie konfiguracji z pliku
// hibernate.cfg.xml
sessionFactory = new Configuration().configure().
BuildSessionFactory();
} catch (Throwable ex) {
System.err.println("failure " + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Struktura przykładu
19
+src
+data
Contractor.java
Contractor.hbm.xml
Order.java
Order.hbm.xml
ContractorManager.java
OrderManager.java
+util
HibernateUtil.java
Example.java
hibermate.cfg.xml
log4j.properties
Example.java
20
public class Example {
public static void main(String[] args) {
ContractorManager cm = new ContractorManager();
if (args[0].equals("create")) {
Contractor c1, c2;
cm.create("Adam", "Lesna 11/3");
cm.create("Tomasz", "Zielona 123/65");
cm.create("Pawel", "Krotka 6");
c1 = cm.load(1); c2 = cm.load(2);
OrderManager om = new OrderManager();
om.create(c1);
om.create(c2);
om.create(c1);
}
Example.java
21
else if (args[0].equals("print")) {
Order o;
Session session = HibernateUtil.getSessionFactory().
GetCurrentSession();
session.beginTransaction();
List l = session.createQuery(
"from Contractor").list();
for (int i = 0; i < l.size(); i++) {
Contractor c = (Contractor) l.get(i);
System.out.println("Contractor:");
System.out.println(String.valueOf(c.getId()) +
", " + String.valueOf(c.getName()) +
", " + String.valueOf(c.getAddress()));
Example.java
22
for( Iterator it = c.getOrders().iterator();
it.hasNext(); ){
o = (Order) it.next();
System.out.println("Order: " +
String.valueOf(o.getId()) +
", " + o.getDate());
}
}
session.getTransaction().commit();
}
HibernateUtil.getSessionFactory().close();
}
}
Hibernate.cfg.xml
23
Plik
hibernate.cfg.xml
określa konfigurację biblioteki Hibernate:
<?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>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost/example
</property>
Hibernate.cfg.xml
24
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">1</property>
<
property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="current_session_context_class">
thread
</property>
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
Hibernate.cfg.xml
25
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="data/Contractor.hbm.xml"/>
<mapping resource="data/Order.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Uruchomienie przykładu
26
Niezbędne biblioteki:
antlr.jar
asm.jar
asm-attrs.jars
cglib.jar
commons-collections.jar
commons-logging.jar
dom4j.jar
hibernate3.jar
jta.jar
log4j.jar
mysql-connector-java-3.1.8
pierwsze uruchomienie spowoduje utworzenie odpowiednich tabel:
java -cp [biblioteki] Example create
Uruchomienie przykładu
27
...
08:35:52,777 INFO Configuration:1308 - configuring from resource:
/hibernate.cfg.xml
...
08:35:52,924 INFO Configuration:469 - Reading mappings from resource:
data/Contractor.hbm.xml
08:35:53,083 INFO HbmBinder:309 - Mapping class: data.Contractor ->
contractors
08:35:53,144 INFO Configuration:469 - Reading mappings from resource:
data/Order.hbm.xml
08:35:53,207 INFO HbmBinder:309 - Mapping class: data.Order -> orders
08:35:53,207 INFO HbmBinder:309 - Mapping class: data.Order -> orders
...
...
08:35:53,329 INFO HbmBinder:2349 - Mapping collection: data.Contractor.orders
08:35:53,329 INFO HbmBinder:2349 - Mapping collection: data.Contractor.orders
-> orders
-> orders
...
...
08:35:53,360 INFO DriverManagerConnectionProvider:80 - using driver:
08:35:53,360 INFO DriverManagerConnectionProvider:80 - using driver:
com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/example
com.mysql.jdbc.Driver at URL: jdbc:mysql://localhost/example
08:35:53,361 INFO DriverManagerConnectionProvider:86 - connection properties:
08:35:53,361 INFO DriverManagerConnectionProvider:86 - connection properties:
{user=root, password=****}
{user=root, password=****}
Uruchomienie przykładu
28
...
...
08:35:55,199 DEBUG SchemaExport:301 - create table contractors (con_id integer
08:35:55,199 DEBUG SchemaExport:301 - create table contractors (con_id integer
not null auto_increment, con_name varchar(255), con_address varchar(255),
not null auto_increment, con_name varchar(255), con_address varchar(255),
primary key (con_id))
primary key (con_id))
08:35:55,205 DEBUG SchemaExport:301 - create table orders (odr_id integer not
08:35:55,205 DEBUG SchemaExport:301 - create table orders (odr_id integer not
null auto_increment, odr_date date, con_id integer, primary key (odr_id))
null auto_increment, odr_date date, con_id integer, primary key (odr_id))
08:35:55,213 DEBUG SchemaExport:301 - alter table orders add index
08:35:55,213 DEBUG SchemaExport:301 - alter table orders add index
FKC3DF62E5B8CC0851 (con_id), add constraint FKC3DF62E5B8CC0851 foreign key
FKC3DF62E5B8CC0851 (con_id), add constraint FKC3DF62E5B8CC0851 foreign key
(con_id) references contractors (con_id)
(con_id) references contractors (con_id)
...
...
Hibernate: insert into contractors (con_name, con_address) values (?, ?)
Hibernate: insert into contractors (con_name, con_address) values (?, ?)
Hibernate: insert into contractors (con_name, con_address) values (?, ?)
Hibernate: insert into contractors (con_name, con_address) values (?, ?)
Hibernate: insert into contractors (con_name, con_address) values (?, ?)
Hibernate: insert into contractors (con_name, con_address) values (?, ?)
Hibernate: insert into orders (odr_date, con_id) values (?, ?)
Hibernate: insert into orders (odr_date, con_id) values (?, ?)
Hibernate: insert into orders (odr_date, con_id) values (?, ?)
Hibernate: insert into orders (odr_date, con_id) values (?, ?)
Hibernate: insert into orders (odr_date, con_id) values (?, ?)
Hibernate: insert into orders (odr_date, con_id) values (?, ?)
08:35:55,740 INFO SessionFactoryImpl:729 - closing
08:35:55,744 INFO DriverManagerConnectionProvider:147 - cleaning up
connection pool: jdbc:mysql://localhost/example
Uruchomienie przykładu
29
Drugie uruchomienie programu:
●
z pliku hibernate.cfg.xml usówamy element:
<property name="hbm2ddl.auto">create</property>
●
java -cp [biblioteki] Example print
Hibernate: select contractor0_.con_id as con1_0_,
contractor0_.con_name as con2_0_, contractor0_.con_address as
con3_0_ from contractors contractor0_
Contractor:
1, Adam, Lesna 11/3
Hibernate: select orders0_.con_id as con3_1_, orders0_.odr_id
as odr1_1_, orders0_.odr_id as odr1_1_0_, orders0_.odr_date as
odr2_1_0_, orders0_.con_id as con3_1_0_ from orders orders0_
where orders0_.con_id=?
Order: 3, 2006-04-11
Order: 1, 2006-04-11
Contractor:
...
Podsumowanie
30
Hibernate jest obecnie standardem w dziedzinie ORM. Biblioteka ta jest
odpowiedzialna za zarządzanie trwałymi obiektami w ramach technologii J2EE.
Istnieje także jej wersja dla środowiska .NET.