Upload
benfante
View
1.642
Download
0
Tags:
Embed Size (px)
DESCRIPTION
La persistenza dei dati è una caratteristica fondamentale di ogni applicazione, e quasi sempre la scelta ricade sull’utilizzo di un database relazionale. Java, fin dalle sue prime versioni, ha avuto a disposizione la libreria JDBC per accedere a tale tipo di database. In questa presentazione si mostrerà come utilizzare la libreria JDBC, mostrandone pregi e limiti. In seguito si mostrerà l’utilizzo tradizionale di Hibernate, forse il più famoso e diffuso degli Object/Relational Mapper (ORM), che permettono di trattare i dati relazionali inserendoli all’interno di oggetti. Infine si introdurrà la Java Persistence API (JPA), la libreria di persistenza ORM introdotta con la Java Enterprise Edition (JEE) 5.
Citation preview
Java e i database: da JDBC a JPALucio Benfante
lucio benfante.com@
verona.javaday.it www.jugpadova.it
database...chi era costui?
Application 1
The database and the applications
database
Application 2
Application 3
anotherdb
Atomicity
Consistency
Isolation
Durability
personid first_name last_name father born_in
1 Lucio Benfante 101
2 Giacomo Puccini 3 102
3 Michele Puccini 102
4 Antonio Puccini 2 103
city
id name
101 Venezia
102 Lucca
103 Milano
Relational databases
father
0
n
born_in_city
n 1
The term relational database was originally defined and coined by Edgar Codd at IBM Almaden Research Center in 1970.
SQL: Structured Query Language
SELECT first_name, last_name FROM person WHERE last_name = 'Puccini' ORDER BY first_name;
INSERT INTO person VALUES (5, 'Mario', 'Rossi', NULL, NULL);
DELETE FROM person WHERE id = ;1
UPDATE person SET first_name = 'Carlo' WHERE id = ;1
...and much more, included Data Definition Language (DDL).
RelationalDatabase Management Systems (DBMS)
DB2
InformixDynamic Server
DBMSApplication
specificDBMS
protocol
(just a small selection)
Java DataBase Connectivity(JDBC)
OracleDBMS
protocol
Application
OracleDBMS
OracleJDBC Driver
PostgreSQLJDBC Driver
PostgreSQLDBMS
PostgreSQLDBMS
protocol
JDBC API
JDBC Getting a connection
Class.forName("org.postgresql.Driver" );
Connection con = DriverManager.getConnection ( “jdbc:postgresql://localhost/javaday”, “username”, “password”);
JDBCExecuting an SQL statement
PreparedStatement ps = con.prepareStatement( "SELECT FROM Person WHERE last_name=* ?”);
ps.setString( , 1 "Puccini");
ResultSet rs = ps.executeQuery();
JDBCRetrieving your data
while ( rs.next() ) {
String firstName = rs.getString(“first_name”);
String lastName = rs.getString(“last_name”);
long fatherId = rs.getLong(“father”);
...etc.etc....}
JDBCAll together
Connection con=null;try { Class.forName( "com.mioDbms.mioDriver" ); con = DriverManager.getConnection ( “jdbc:...”, “user”, “pass”); PreparedStatement ps = con.prepareStatement( "SELECT FROM Person WHERE name=?”);* ps.setString( , "Lucio Benfante");1 ResultSet rs = ps.executeQuery(); while ( rs.next() ) rs.getString...ecc..ecc.... { } rs.close(); ps.close(); stmt.close(); catch(Exception e) ...} { finally } {
try { If (con != null) { con.close(); } catch( Exception ignoreMe ) } {}}
Object Relational Mapping (ORM)
ORM
HibernateMapping with XML
class name="Person" table="PERSON"< > id name="id" column="ID"< > generator class="native"/< > /id< > property name="firstName" column=”FIRST_NAME”/< > property name="lastName" column=”LAST_NAME”/< > many-to-one name=”father”< column=”FATHER”/> many-to-one name=”bornIn”< column=”BORN_IN” class=”City”/>/class< >
HibernateGetting your objects
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();Transaction tx = session.beginTransaction();Query q = session.createQuery( “from Person p where p.lastName = :lastName”);q.setString(“lastName”, “Puccini”);List people = q.list();// here you'll have a list of persistent Person objects
Person person = ((Person)people.get( ))0City city = person.getBornIn();person.setFirstName(“Pippo”);
tx.commit();session.close();
sf.close();
HibernateCreating new records
Session session = sf.openSession();Transaction tx = session.beginTransaction();
Person person = new Person(“Lucio”, “Benfante”);session.save(person);
tx.commit();session.close();
HibernateConfiguration
!DOCTYPE hibernate-configuration PUBLIC<"-//Hibernate/Hibernate Configuration DTD 3. //EN"0"http://hibernate.sourceforge.net/hibernate-configuration-3. .dtd"0 >hibernate-configuration < >
session-factory< > !-- Database connection settings --< > property name=< "connection.driver_class">org.postgresql.Driver /property< > property name=< "connection.url">jdbc:postgresql://localhost/javaday /property< > property name=< "connection.username">username /property< > property name=< "connection.password">password /property< > !-- SQL dialect --< > property name=< "dialect">org.hibernate.dialect.PostgreSQLDialect /property< > !-- Echo all executed SQL to stdout --< > property name="show_sql" true /property< > < > !-- Create/Update the database schema on startup --< > property name=< "hbm2ddl.auto">update /property< > mapping resource=< "com/myproject/Person.hbm.xml"/> mapping resource=< "com/myproject/City.hbm.xml"/> /session-factory< >/hibernate-configuration< >
Look at our layers now
OracleDBMS
protocol
Application
OracleDBMS
OracleJDBC Driver
PostgreSQLJDBC Driver
PostgreSQLDBMS
PostgreSQLDBMS
protocol
JDBC API
ORM
●Hibernate●iBatis●JPA
− Hibernate− Toplink Essentials− EclipseLink− OpenJPA
●...
Java Persistence API (JPA)
A standard ORM in Java Enterprise Edition (JEE5)
JPAMapping with annotations
Entity@public class Person implements Serializable { Id@ GeneratedValue(strategy = GenerationType.AUTO)@ Basic(optional = false)@ private Integer id;
Column(name = "first_name")@ private String firstName;
Column(name = "last_name")@ private String lastName;
JoinColumn(name = "born_in", referencedColumnName = "id")@ ManyToOne@ private City bornIn;
OneToMany(mappedBy = "father")@ private Collection Person children;< >
JoinColumn(name = "father", referencedColumnName = "id")@ ManyToOne@ private Person father;
// ... normal getters and setters
// equals and hashCode implementation}
Hibernateor
JPA?
References
● www.hibernate.org
● http://java.sun.com/docs/books/tutorial/jdbc/index.html
● http://java.sun.com/javaee/5/docs/tutorial/doc/
● “Java Persistence with Hibernate”, Christian Bauer and Gavin King, Manning, 2007
● www.parancoe.org