SlideShare ist ein Scribd-Unternehmen logo
1 von 21
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
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
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdfChristopherTHyatt
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
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 FresherRemote DBA Services
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
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
 

Kürzlich hochgeladen (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
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...
 
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...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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
 

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