Java e i database: da JDBC a JPA


Published on

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.

Published in: Technology
  • Be the first to comment

  • Be the first to like this

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Java e i database: da JDBC a JPA

  1. 1. Java e i database: da JDBC a JPA Lucio Benfante
  2. 2. database...chi era costui?
  3. 3. The database and the applications database Application 1 Application 3 Application 2 Atomicity another Consistency db Isolation Durability
  4. 4. Relational databases person city id first_name last_name father born_in id name n 1 Lucio Benfante 101 n 1 101 Venezia 2 Giacomo Puccini 3 102 born_in_city 102 Lucca 3 Michele Puccini 102 4 Antonio Puccini 2 103 103 Milano 0 father The term relational database was originally defined and coined by Edgar Codd at IBM Almaden Research Center in 1970.
  5. 5. 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); UPDATE person SET first_name = 'Carlo' WHERE id = 1; DELETE FROM person WHERE id = 1; ...and much more, included Data Definition Language (DDL).
  6. 6. Relational Database Management Systems (DBMS) Informix DB2 Dynamic Server (just a small selection) specific DBMS protocol Application DBMS
  7. 7. Java DataBase Connectivity (JDBC) Application JDBC API PostgreSQL Oracle JDBC Driver JDBC Driver PostgreSQL Oracle DBMS DBMS protocol protocol PostgreSQL Oracle DBMS DBMS
  8. 8. JDBC Getting a connection Class.forName("org.postgresql.Driver" ); Connection con = DriverManager.getConnection ( “jdbc:postgresql://localhost/javaday”, “username”, “password”);
  9. 9. JDBC Executing an SQL statement PreparedStatement ps = con.prepareStatement( "SELECT * FROM Person WHERE last_name=?”); ps.setString(1, "Puccini"); ResultSet rs = ps.executeQuery();
  10. 10. JDBC Retrieving your data while ( ) { String firstName = rs.getString(“first_name”); String lastName = rs.getString(“last_name”); long fatherId = rs.getLong(“father”); ...etc.etc.... }
  11. 11. JDBC All 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(1, "Lucio Benfante"); ResultSet rs = ps.executeQuery(); while ( ) { rs.getString...ecc..ecc.... } rs.close(); ps.close(); stmt.close(); } catch(Exception e){ ... } finally { try { If (con != null) { con.close(); } } catch( Exception ignoreMe ) {} }
  12. 12. Object Relational Mapping (ORM) ORM
  13. 13. Hibernate Mapping 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>
  14. 14. Hibernate Getting 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(0)) City city = person.getBornIn(); person.setFirstName(“Pippo”); tx.commit(); session.close(); sf.close();
  15. 15. Hibernate Creating new records Session session = sf.openSession(); Transaction tx = session.beginTransaction(); Person person = new Person(“Lucio”, “Benfante”);; tx.commit(); session.close();
  16. 16. Hibernate Configuration <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" ""> <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="">update</property> <mapping resource="com/myproject/Person.hbm.xml"/> <mapping resource="com/myproject/City.hbm.xml"/> </session-factory> </hibernate-configuration>
  17. 17. Look at our layers now Application ●Hibernate ●iBatis ●JPA ORM − Hibernate − Toplink Essentials JDBC API − EclipseLink PostgreSQL Oracle − OpenJPA JDBC Driver JDBC Driver ... ● PostgreSQL Oracle DBMS DBMS protocol protocol PostgreSQL Oracle DBMS DBMS
  18. 18. Java Persistence API (JPA) A standard ORM in Java Enterprise Edition (JEE5)
  19. 19. JPA Mapping 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 }
  20. 20. Hibernate or JPA?
  21. 21. References ● ● ● ● “Java Persistence with Hibernate”, Christian Bauer and Gavin King, Manning, 2007 ●