SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

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

Semelhante 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
 

Semelhante 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

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 

Último (20)

Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 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