SlideShare a Scribd company logo
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

More Related Content

PDF
hibernate
PDF
JPA2 - a brief intro
PPTX
Jdbc
PDF
Java Future S Ritter
PDF
Java Programming Guide Quick Reference
PDF
Jruby - Ruby em Ambientes 100% Java
PPT
PPS
Dacj 4 2-b
hibernate
JPA2 - a brief intro
Jdbc
Java Future S Ritter
Java Programming Guide Quick Reference
Jruby - Ruby em Ambientes 100% Java
Dacj 4 2-b

What's hot (13)

PDF
Java Cheat Sheet
PDF
Introduction to JDBC and database access in web applications
DOCX
Java cheat sheet
PPS
Dacj 4 2-c
PDF
PPT
VNSISPL_DBMS_Concepts_ch4
PDF
FrOScamp Zurich: Introducing JCR - 2010
PPT
Jdbc sasidhar
PPTX
Django - sql alchemy - jquery
PDF
VJET bringing the best of Java and JavaScript together
PDF
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
PDF
Curious case of Dust
Java Cheat Sheet
Introduction to JDBC and database access in web applications
Java cheat sheet
Dacj 4 2-c
VNSISPL_DBMS_Concepts_ch4
FrOScamp Zurich: Introducing JCR - 2010
Jdbc sasidhar
Django - sql alchemy - jquery
VJET bringing the best of Java and JavaScript together
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
Curious case of Dust
Ad

Viewers also liked (9)

PDF
Annotated controllers with Spring MVC 2.5
PDF
Got bored by the relational database? Switch to a RDF store!
ODP
Parancoe and Lambico
PPTX
Knowledge base – direc tv’s naso development
PDF
Java Persistence 2.0
ODP
Applicazione JavaFX – CORSA DI AUTO SU TRACCIATI REALI
PDF
Digital Cartel (D.C) Corporate Profile
PPTX
Steve Jobs
PPT
Milieu
Annotated controllers with Spring MVC 2.5
Got bored by the relational database? Switch to a RDF store!
Parancoe and Lambico
Knowledge base – direc tv’s naso development
Java Persistence 2.0
Applicazione JavaFX – CORSA DI AUTO SU TRACCIATI REALI
Digital Cartel (D.C) Corporate Profile
Steve Jobs
Milieu
Ad

Similar to Java e i database: da JDBC a JPA (20)

PPT
High Performance Jdbc
PDF
High performance database applications with pure query and ibm data studio.ba...
PDF
PPT
Basic Hibernate Final
PPT
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
PPTX
Module-3 for career and JFSD ppt for study.pptx
PPTX
SeaJUG May 2012 mybatis
PDF
Apache Con Us2007 Apachei Batis
 
PDF
Alternatives of JPA/Hibernate
PDF
Free Hibernate Tutorial | VirtualNuggets
PDF
Java Web Programming [3/9] : Servlet Advanced
PPT
JDBC Connectivity Model
PPTX
Hibernate in XPages
PPTX
Advance java session 5
PDF
Java Web Programming Using Cloud Platform: Module 3
PDF
Tutorial On Database Management System
PDF
Introduction to JPA and Hibernate including examples
PDF
SQL, NoSQL, NewSQL? What's a developer to do?
PDF
Hibernate 3
PDF
Java persistence api 2.1
High Performance Jdbc
High performance database applications with pure query and ibm data studio.ba...
Basic Hibernate Final
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Module-3 for career and JFSD ppt for study.pptx
SeaJUG May 2012 mybatis
Apache Con Us2007 Apachei Batis
 
Alternatives of JPA/Hibernate
Free Hibernate Tutorial | VirtualNuggets
Java Web Programming [3/9] : Servlet Advanced
JDBC Connectivity Model
Hibernate in XPages
Advance java session 5
Java Web Programming Using Cloud Platform: Module 3
Tutorial On Database Management System
Introduction to JPA and Hibernate including examples
SQL, NoSQL, NewSQL? What's a developer to do?
Hibernate 3
Java persistence api 2.1

Recently uploaded (20)

PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Encapsulation theory and applications.pdf
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Machine learning based COVID-19 study performance prediction
PDF
KodekX | Application Modernization Development
PPT
Teaching material agriculture food technology
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Encapsulation theory and applications.pdf
sap open course for s4hana steps from ECC to s4
Review of recent advances in non-invasive hemoglobin estimation
Digital-Transformation-Roadmap-for-Companies.pptx
Encapsulation_ Review paper, used for researhc scholars
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Machine learning based COVID-19 study performance prediction
KodekX | Application Modernization Development
Teaching material agriculture food technology
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Unlocking AI with Model Context Protocol (MCP)
Reach Out and Touch Someone: Haptics and Empathic Computing
Building Integrated photovoltaic BIPV_UPV.pdf
NewMind AI Weekly Chronicles - August'25 Week I
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Spectral efficient network and resource selection model in 5G networks
Network Security Unit 5.pdf for BCA BBA.
Mobile App Security Testing_ A Comprehensive Guide.pdf
MIND Revenue Release Quarter 2 2025 Press Release

Java e i database: da JDBC a JPA

  • 1. Java e i database: da JDBC a JPA Lucio Benfante lucio@benfante.com verona.javaday.it www.jugpadova.it
  • 3. The database and the applications database Application 1 Application 3 Application 2 Atomicity another Consistency db Isolation Durability
  • 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. 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. Relational Database Management Systems (DBMS) Informix DB2 Dynamic Server (just a small selection) specific DBMS protocol Application DBMS
  • 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. JDBC Getting a connection Class.forName("org.postgresql.Driver" ); Connection con = DriverManager.getConnection ( “jdbc:postgresql://localhost/javaday”, “username”, “password”);
  • 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. 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.... }
  • 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.next() ) { rs.getString...ecc..ecc.... } rs.close(); ps.close(); stmt.close(); } catch(Exception e){ ... } finally { try { If (con != null) { con.close(); } } catch( Exception ignoreMe ) {} }
  • 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. 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. 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();
  • 16. 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>
  • 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. Java Persistence API (JPA) A standard ORM in Java Enterprise Edition (JEE5)
  • 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. Hibernate or JPA?
  • 21. 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