Java e i database: da JDBC a JPA
Upcoming SlideShare
Loading in...5
×
 

Java e i database: da JDBC a JPA

on

  • 2,589 views

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 ...

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.

Statistics

Views

Total Views
2,589
Views on SlideShare
2,578
Embed Views
11

Actions

Likes
0
Downloads
75
Comments
0

2 Embeds 11

http://www.slideshare.net 8
http://www.techgig.com 3

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

CC Attribution-NonCommercial-ShareAlike LicenseCC Attribution-NonCommercial-ShareAlike LicenseCC Attribution-NonCommercial-ShareAlike License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Java e i database: da JDBC a JPA Java e i database: da JDBC a JPA Presentation Transcript

  • Java e i database: da JDBC a JPA Lucio Benfante lucio@benfante.com verona.javaday.it www.jugpadova.it
  • database...chi era costui?
  • The database and the applications database Application 1 Application 3 Application 2 Atomicity another Consistency db Isolation Durability
  • 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.
  • 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).
  • Relational Database Management Systems (DBMS) Informix DB2 Dynamic Server (just a small selection) specific DBMS protocol Application DBMS
  • Java DataBase Connectivity (JDBC) Application JDBC API PostgreSQL Oracle JDBC Driver JDBC Driver PostgreSQL Oracle DBMS DBMS protocol protocol PostgreSQL Oracle DBMS DBMS
  • JDBC Getting a connection Class.forName("org.postgresql.Driver" ); Connection con = DriverManager.getConnection ( “jdbc:postgresql://localhost/javaday”, “username”, “password”);
  • JDBC Executing an SQL statement PreparedStatement ps = con.prepareStatement( "SELECT * FROM Person WHERE last_name=?”); ps.setString(1, "Puccini"); ResultSet rs = ps.executeQuery();
  • JDBC Retrieving your data while ( rs.next() ) { String firstName = rs.getString(“first_name”); String lastName = rs.getString(“last_name”); long fatherId = rs.getLong(“father”); ...etc.etc.... }
  • 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.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
  • 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>
  • 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();
  • Hibernate Creating new records Session session = sf.openSession(); Transaction tx = session.beginTransaction(); Person person = new Person(“Lucio”, “Benfante”); session.save(person); tx.commit(); session.close();
  • Hibernate Configuration <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <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 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
  • Java Persistence API (JPA) A standard ORM in Java Enterprise Edition (JEE5)
  • 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 }
  • Hibernate or 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