SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

VJET bringing the best of Java and JavaScript together
VJET bringing the best of Java and JavaScript togetherVJET bringing the best of Java and JavaScript together
VJET bringing the best of Java and JavaScript together
Justin Early
 
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
Vladimir Bacvanski, PhD
 

Tendances (13)

Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat Sheet
 
Introduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applicationsIntroduction to JDBC and database access in web applications
Introduction to JDBC and database access in web applications
 
Java cheat sheet
Java cheat sheet Java cheat sheet
Java cheat sheet
 
Dacj 4 2-c
Dacj 4 2-cDacj 4 2-c
Dacj 4 2-c
 
Jdbc
JdbcJdbc
Jdbc
 
VNSISPL_DBMS_Concepts_ch4
VNSISPL_DBMS_Concepts_ch4VNSISPL_DBMS_Concepts_ch4
VNSISPL_DBMS_Concepts_ch4
 
FrOScamp Zurich: Introducing JCR - 2010
FrOScamp Zurich: Introducing JCR - 2010FrOScamp Zurich: Introducing JCR - 2010
FrOScamp Zurich: Introducing JCR - 2010
 
Java beans
Java beansJava beans
Java beans
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Django - sql alchemy - jquery
Django - sql alchemy - jqueryDjango - sql alchemy - jquery
Django - sql alchemy - jquery
 
VJET bringing the best of Java and JavaScript together
VJET bringing the best of Java and JavaScript togetherVJET bringing the best of Java and JavaScript together
VJET bringing the best of Java and JavaScript together
 
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
Crash Introduction to Modern Java Data Access: Understanding JPA, Hibernate, ...
 
Curious case of Dust
Curious case of DustCurious case of Dust
Curious case of Dust
 

En vedette

Got bored by the relational database? Switch to a RDF store!
Got bored by the relational database? Switch to a RDF store!Got bored by the relational database? Switch to a RDF store!
Got bored by the relational database? Switch to a RDF store!
benfante
 
Knowledge base – direc tv’s naso development
Knowledge base – direc tv’s naso developmentKnowledge base – direc tv’s naso development
Knowledge base – direc tv’s naso development
jericbd
 
Digital Cartel (D.C) Corporate Profile
Digital Cartel (D.C) Corporate ProfileDigital Cartel (D.C) Corporate Profile
Digital Cartel (D.C) Corporate Profile
Hammad Khan
 

En vedette (9)

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

Similaire à Java e i database: da JDBC a JPA

Enterprise Java Web Application Frameworks Sample Stack Implementation
Enterprise Java Web Application Frameworks   Sample Stack ImplementationEnterprise Java Web Application Frameworks   Sample Stack Implementation
Enterprise Java Web Application Frameworks Sample Stack Implementation
Mert Çalışkan
 
High Performance Jdbc
High Performance JdbcHigh Performance Jdbc
High Performance Jdbc
Sam Pattsin
 

Similaire à Java e i database: da JDBC a JPA (20)

JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
JDBC
JDBCJDBC
JDBC
 
JDBC Part - 2
JDBC Part - 2JDBC Part - 2
JDBC Part - 2
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
Lecture17
Lecture17Lecture17
Lecture17
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2
 
JDBC (2).ppt
JDBC (2).pptJDBC (2).ppt
JDBC (2).ppt
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Jdbc
JdbcJdbc
Jdbc
 
Enterprise Java Web Application Frameworks Sample Stack Implementation
Enterprise Java Web Application Frameworks   Sample Stack ImplementationEnterprise Java Web Application Frameworks   Sample Stack Implementation
Enterprise Java Web Application Frameworks Sample Stack Implementation
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
Hibernate
Hibernate Hibernate
Hibernate
 
iPhonical and model-driven software development for the iPhone
iPhonical and model-driven software development for the iPhoneiPhonical and model-driven software development for the iPhone
iPhonical and model-driven software development for the iPhone
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015
 
Jdbc
Jdbc   Jdbc
Jdbc
 
High Performance Jdbc
High Performance JdbcHigh Performance Jdbc
High Performance Jdbc
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 

Dernier

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Dernier (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 

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