SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

Java Cheat Sheet
Java Cheat SheetJava Cheat Sheet
Java Cheat SheetGlowTouch
 
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 applicationsFulvio Corno
 
VNSISPL_DBMS_Concepts_ch4
VNSISPL_DBMS_Concepts_ch4VNSISPL_DBMS_Concepts_ch4
VNSISPL_DBMS_Concepts_ch4sriprasoon
 
FrOScamp Zurich: Introducing JCR - 2010
FrOScamp Zurich: Introducing JCR - 2010FrOScamp Zurich: Introducing JCR - 2010
FrOScamp Zurich: Introducing JCR - 2010David Nuescheler
 
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 togetherJustin 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
 

La actualidad más candente (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
 

Destacado

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.5benfante
 
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
 
Parancoe and Lambico
Parancoe and LambicoParancoe and Lambico
Parancoe and Lambicobenfante
 
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 developmentjericbd
 
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 REALIbenfante
 
Digital Cartel (D.C) Corporate Profile
Digital Cartel (D.C) Corporate ProfileDigital Cartel (D.C) Corporate Profile
Digital Cartel (D.C) Corporate ProfileHammad Khan
 

Destacado (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
 

Similar a Java e i database: da JDBC a JPA

JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
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 JavaPawanMM
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivityAtul Saurabh
 
Spring framework part 2
Spring framework part 2Spring framework part 2
Spring framework part 2Haroon Idrees
 
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 ImplementationMert Çalışkan
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data AccessDzmitry Naskou
 
Hibernate
Hibernate Hibernate
Hibernate Sunil OS
 
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 iPhoneHeiko Behrens
 
Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Entity Framework: Nakov @ BFU Hackhaton 2015
Entity Framework: Nakov @ BFU Hackhaton 2015Svetlin Nakov
 
High Performance Jdbc
High Performance JdbcHigh Performance Jdbc
High Performance JdbcSam Pattsin
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 

Similar a 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
 

Último

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
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 educationjfdjdjcjdnsjd
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
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, Adobeapidays
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 

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