SlideShare a Scribd company logo
1 of 49
Download to read offline
JPA and Hibernate

        Mike Calvo
mike@citronellasoftware.com
What is JPA?
• Java Persistence API
• A specification for generic ORM
  – Not an implementation
  – Vendor-neutral
• Based on Annotations
  – Metadata
• Developed out of EJB 3 Specification
  – Replacement for train wreck EJB 2 persistence
  – Stand alone specification (does not require JEE
    container)
What is Hibernate?
•   Very popular open source Java ORM tool
•   Originally developed by Gavin King
•   Now maintained by Redhat (JBoss Group)
•   Implements JPA specification
•   Predates JPA
    – Has its own custom API for persisting mapped
      objects
Choosing an API
• JPA Benefits
  – Standard
  – Vendor-neutral
  – Works with EJB 3
• Hibernate Benefits
  – More mature (fully developed)
  – Works with Java 1.4 and older
• My Policy
  – Use JPA when you can
  – Use Hibernate API when you need it
Enabling Hibernate & JPA with Maven
        <dependency>
           <groupId>org.hibernate</groupId>
           <artifactId>hibernate</artifactId>
           <version>3.2.5.ga</version>
         </dependency>

         <dependency>
           <groupId>org.hibernate</groupId>
           <artifactId>hibernate-annotations</artifactId>
           <version>3.3.0.ga</version>
         </dependency>

         <dependency>
           <groupId>org.hibernate</groupId>
           <artifactId>hibernate-entitymanager</artifactId>
           <version>3.3.1.ga</version>
         </dependency>
Configuring Mapping
• Hibernate legacy
  – XML configuration files
  – Each file mapped a class and it’s persistent fields
• JPA and Hibernate 3.2 and above
  – Annotations (javax.persistence package)
  – Class-level: marks a class as persistent
  – Method/File level: configure field and relationship
    persistence
• Hibernate still supports XML configuration
Core JPA Annotations
•   @Entity
•   @Id
•   @GeneratedValue
•   @Column
•   @JoinColumn
•   @OneToMany
•   @ManyToOne
•   @ManyToMany
JPA Annotation Rules
• Any persistent class must be annotated with @Entity
  (or inherit from a class that does)
• All persistent classes must have a field annotated by
  @Id signifying the primary key
• All instance fields in a persistent class are assumed to
  be mapped to columns with the same name as the
  field
   – @Transient will remove a field from mapping
• Relationships are not automatically mapped
   – Relationships are modeled as aggregate members
   – Require an @OneToMany, @ManyToOne, or
     @ManyToMany
Overriding Defaults
• Class annotation @Table defines specific table
  mappings
  – Name
• Field annotation @Column defines specific
  column mappings
  – Name
  – Nullability
  – Size
  – Uniqueness
Relationships
• @OneToMany
  – Annotate a member variable which is an @Entity
    annotated type
• @ManyToOne or @ManyToMany
  – Annotate a member variable which is a standard Java
    collection with parameter of type which is an @Entity
  – Type of collection is significant
• Use @JoinColumn to define specifics about the
  join column
Relationship Features
•   Lazy Loading and Fetch
•   Cascading
•   Fetch
•   Polymorphic
Lazy Loading
• Performance optimization
• Related items are not retrieved until they are
  first accessed
  – Field level access
• Limited to work only within the Session or
  EntityManager that loaded the parent object
  – Causes a big problem in web applications
Fetch
• Fetch mode
  – Lazy
  – Eager – disable lazy loading
• Mode can be configured on each relationship
• Consider performance and use when configuring
  fetch
Cascade
• Tells Hibernate whether to follow the path of
  the relationship on
  – Insert
  – Update
  – Delete
  – All
• Hibernate adds options
  – Delete All Orphans
Inheritance
• JPA and Hibernate support mapping Class
  inheritance to relational tables
• Three approaches provided:
  – Table per class hierarchy
  – Table per sub class
  – Table per concrete class
Table per Class Hierarchy
• All of the data representing the properties of
  every class in the Hierarchy are stored in one
  table
• Requires that columns representing fields in
  subclasses allow null
• Uses discriminator column to determine the
  type of object represented a row
  – Each subclass must declare the discriminator
    value for the type
Table per Class Hierarchy Example
• Patient and Physician extend Person
Patient and Person
Resultant DDL




Has fields for both Patient and Physician
Table per Subclass
• Each subclass in the hierarchy gets its own
  table
• Parent class fields are in one table
• Primary key in subclass tables refer back to
  the parent class table
• Use joined-subclass configuration
Table per Subclass Example
• CreditCardPayment, CashPayment, and
  CheckPayment all extend Payment
Payment Subclasses
Table Per Subclass DDL
Discriminator w/Table Per Subclass
• Table per subclass also supports the use of a
  discriminator
• Not required
Table per Concrete Class
• Each class in the hierarchy gets its own table
• The parent class fields are duplicated in each
  table
• Two approaches
  – Union subclass
  – Implicit polymorphism
Union Subclass
• Map the Parent class as normal
  – No discriminator required
  – Specify parent class properties
  – @Inheritance(strategy =
    InheritanceType.TABLE_PER_CLASS)
• Map each of the subclasses
  – Specify a table name
  – Specify subclass properties
Implicit Polymorphism
• Parent class is not mapped using hibernate
  – Annotate with @MappedSuperclass
• Each of the subclasses is mapped as a normal
  class
  – Map all of the properties, including the parent
    properties
Implicit Polymorphism Example
• Car and Truck extend Vehicle
• SUV extends Truck
Vehicle Parent Class
• Class not mapped, but properties are
Vehicle Subclasses
Implicit Polymorphism DDL
Persistence Configuration Files
• Used to define application persistence properties
  –   Database connection information
  –   Dialect (database-specific language)
  –   Logging
  –   Schema creation parameters
• Default location is in CLASSPATH
• JPA
  – META-INF/persistence.xml
• Hibernate
  – hibernate.cfg.xml
Example persistence.xml
<persistence xmlns=quot;http://java.sun.com/xml/ns/persistencequot;
 xmlns:xsi=quot;http://www.w3.org/2001/XMLSchema-instancequot;
 xsi:schemaLocation=quot;http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsdquot;
 version=quot;1.0quot;>
  <persistence-unit name=“persistence-unitquot;>
       <properties>
       <property name=quot;dialectquot; value=quot;org.hibernate.dialect.DerbyDialectquot;/>
       <property name=quot;hibernate.hbm2ddl.autoquot; value=quot;updatequot;/>
       <property name=quot;hibernate.connection.driver_classquot;
value=quot;org.apache.derby.jdbc.EmbeddedDriverquot;/>
<property name=quot;hibernate.connection.url“ value=quot;jdbc:derby:db;create=truequot;/>
       <property name=quot;hibernate.connection.autocommitquot; value=quot;falsequot; />
     </properties>
  </persistence-unit>
</persistence>
Persistence Core Classes
• Hibernate
  – Configuration -> SessionFactory -> Session
  – Session is gateway to persistence functions
• JPA
  – Persistence -> EntityManagerFactory ->
    EntityManager
  – EntityManager is gateway to persistence functions
EntityManager Functionality
• persist(Obect o)
   – Saves or updates the specified object tree
• remove(Object o)
   – Deletes the specified object
• find(Class type, Serializable id)
   – Retrieves the item of the specified type by id
• merge(Object o)
   – Attaches a detached instance to the manager (required for
     update on item retrieved from a different manager)
• getTransaction()
   – Provides a transaction object to perform commit and
     rollback functions
Querying with JPA
•   JPAQL/HQL
•   Named Queries
•   Criteria
•   By Example
•   Native SQL
JPAQL and HQL
• Query languages that are similar to SQL but are more
  object-centric
• Supports
   –   Selection of object instances from persistent types
   –   Selection of properties (rather than columns)
   –   Polymorphic selection
   –   Automatic joining for nested properties
• Should be very comfortable for those familiar with SQL
• JPAQL is a subset of HQL
   – Hibernate implementation will support both
Example JPAQL/HQL
“from Item i where i.name = ‘foobar’”

“from Item i where i.bidder.name = ‘Mike’” <<< Implicit join

“from Car c where c.coupe = true”

“from Item i where i.bids is not empty”

“from Item i where size(i.bids) > 3” <<< Implicit join

“from Item i order by i.name asc, i.entryDate asc”

“from Item i join i.bids b where b.amount > 100” <<< will return rows with an array

“select distinct(i) from Item i join i.bids b where b.amount > 100” <<< returns Items

“select i.name, i.description from Item i where entryDate > ?”
More JPAQL/HQL Features
• String functions
  – upper, lower, length, substring, concat, trim
• Aggregation functions
  – count, min, max, sum, avg
  – Can require “group by” clause
  – Also supports “having” on “group by”
• Subselects
Query Parameters
• Work just like JDBC Parameters
  – ? Will act as a placeholder for an indexed
    parameter
  – :name will designate a parameter with the name
    of “name”
• Examples
  – select i from Item where name like ?
  – select i from Item where name like :name
Running a JPAQL/HQL Query
• Must be created from the EntityManager or
  Session
  – EntityManger.createQuery(String jpaql)
  – Session.createQuery(String hql)
• Query objects can be configured
  – Maximum number of results
  – Parameters set
• Query objects can then be used to list out the
  results of the query
  – list() returns a java.util.List
Named Queries
• Predefined queries that can be executed by
  name
  – Standard QL used for query
• Defined using @NamedQuery
  – Typically above the persistent class the query is for
  – Defined with name and query values
• Running the query
  – EntityManager.createNamedQuery(name)
  – Session.getNamedQuery(name)
Criteria and Example Queries
• Hibernate only feature
• Full API for programmatically defining the
  query structure using objects
• Created by Session
• Criteria maps all logical restrictions to a query
  as objects and methods
• Example query uses an example object as the
  basis to find other objects
  – Based on Criteria API
Native SQL Queries
• Both JPA and Hibernate support running raw
  SQL
  – Session.createSQLQuery(sql)
  – EntityManager.createNativeQuery(sql)
• Supports specifying the entity type to convert
  the results to
Embeddable Objects
• Some classes contain persistent data, but are
  not true entities
  – Think Data Objects in DDD
• JPA supports this with @Embeddable
  – Annotate your embeddable class
• When your entity needs to store the fields of
  an embeddable class, include an instance of
  that type as a property and annotate it with
  @Embedded
Custom Types
• Sometimes you don’t want the default
  mapping Hibernateassociates with your
  property
• Reasons
  – Combine two fields into one column
  – Numbers and dates stored as strings
  – Data encryption
Creating a UserType
• Implement the org.hibernate.usertype.UserType interface
• returnedClass()
   – Tells Hibernate what type of value to expect for your Type
• sqlTypes()
   – Tells Hibernate what JDBC types you are mapping to
• Key conversion methods
   – nullSafeGet
   – nullSafeSet
   – Have access to
       • JDBC resultSet
       • Column names for property
       • Owning object
Example UserType
• DateAsStringUserType converts dates to
  Strings formatted as yyyy-MM-dd
Other UserType Methods
• equals and hashcode
  – Make sure you check for nulls
• isMutable
  – Are objects of the returned type mutable (Strings are not)
• assemble and disassemble
  – Prepare for/extract from caching
  – Strings can be cached as is (simply return)
• replace
  – Handles a merge
  – Return the first parameter on immutable items

More Related Content

What's hot

What's hot (20)

Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans Spring - Part 1 - IoC, Di and Beans
Spring - Part 1 - IoC, Di and Beans
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Java11 New Features
Java11 New FeaturesJava11 New Features
Java11 New Features
 
JPA For Beginner's
JPA For Beginner'sJPA For Beginner's
JPA For Beginner's
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
REST APIs with Spring
REST APIs with SpringREST APIs with Spring
REST APIs with Spring
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
Java Training | Java Tutorial for Beginners | Java Programming | Java Certifi...
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 

Viewers also liked

ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
Brett Meyer
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
Ram132
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
hr1383
 

Viewers also liked (20)

JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0Overview of JPA (Java Persistence API) v2.0
Overview of JPA (Java Persistence API) v2.0
 
ORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate OverviewORM, JPA, & Hibernate Overview
ORM, JPA, & Hibernate Overview
 
Spring Framework - Data Access
Spring Framework - Data AccessSpring Framework - Data Access
Spring Framework - Data Access
 
JPA - Java Persistence API
JPA - Java Persistence APIJPA - Java Persistence API
JPA - Java Persistence API
 
Hibernate Tutorial
Hibernate TutorialHibernate Tutorial
Hibernate Tutorial
 
Hibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance TechniquesHibernate ORM: Tips, Tricks, and Performance Techniques
Hibernate ORM: Tips, Tricks, and Performance Techniques
 
Hibernate
Hibernate Hibernate
Hibernate
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Hibernate ve jpa
Hibernate ve jpaHibernate ve jpa
Hibernate ve jpa
 
ICT and travel avoidance
ICT and travel avoidanceICT and travel avoidance
ICT and travel avoidance
 
Hibernate ve jpa
Hibernate ve jpaHibernate ve jpa
Hibernate ve jpa
 
EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples - CON7535
EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples - CON7535EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples - CON7535
EJB 3.2/JPA 2.1 Best Practices with Real-Life Examples - CON7535
 
Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"Евгений Капинос "Advanced JPA (Java Persistent API)"
Евгений Капинос "Advanced JPA (Java Persistent API)"
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Hibernate教程
Hibernate教程Hibernate教程
Hibernate教程
 
Spring batch
Spring batchSpring batch
Spring batch
 

Similar to JPA and Hibernate

Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Baruch Sadogursky
 
Automated Performance Testing With J Meter And Maven
Automated  Performance  Testing With  J Meter And  MavenAutomated  Performance  Testing With  J Meter And  Maven
Automated Performance Testing With J Meter And Maven
PerconaPerformance
 
NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)
Samnang Chhun
 

Similar to JPA and Hibernate (20)

T5 Oli Aro
T5 Oli AroT5 Oli Aro
T5 Oli Aro
 
Orbitz and Spring Webflow Case Study
Orbitz and Spring Webflow Case StudyOrbitz and Spring Webflow Case Study
Orbitz and Spring Webflow Case Study
 
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
Persisting Your Objects In The Database World @ AlphaCSP Professional OSS Con...
 
Jsp
JspJsp
Jsp
 
ORM JPA
ORM JPAORM JPA
ORM JPA
 
Jumping Into Java Then!
Jumping Into Java Then!Jumping Into Java Then!
Jumping Into Java Then!
 
Automated Performance Testing With J Meter And Maven
Automated  Performance  Testing With  J Meter And  MavenAutomated  Performance  Testing With  J Meter And  Maven
Automated Performance Testing With J Meter And Maven
 
XML Schema Patterns for Databinding
XML Schema Patterns for DatabindingXML Schema Patterns for Databinding
XML Schema Patterns for Databinding
 
JSUG - Spring by Christoph Pickl
JSUG - Spring by Christoph PicklJSUG - Spring by Christoph Pickl
JSUG - Spring by Christoph Pickl
 
Ridingapachecamel
RidingapachecamelRidingapachecamel
Ridingapachecamel
 
NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)
 
Ext 0523
Ext 0523Ext 0523
Ext 0523
 
Smart Client Development
Smart Client DevelopmentSmart Client Development
Smart Client Development
 
Workin On The Rails Road
Workin On The Rails RoadWorkin On The Rails Road
Workin On The Rails Road
 
70 536
70 53670 536
70 536
 
Lightweight Grids With Terracotta
Lightweight Grids With TerracottaLightweight Grids With Terracotta
Lightweight Grids With Terracotta
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
Entity Persistence with JPA
Entity Persistence with JPAEntity Persistence with JPA
Entity Persistence with JPA
 
Jsf Ajax
Jsf AjaxJsf Ajax
Jsf Ajax
 
Practical catalyst
Practical catalystPractical catalyst
Practical catalyst
 

More from elliando dias

Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
elliando dias
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
elliando dias
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
elliando dias
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
elliando dias
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
elliando dias
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
elliando dias
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
elliando dias
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
elliando dias
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
elliando dias
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
elliando dias
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
elliando dias
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
elliando dias
 

More from elliando dias (20)

Clojurescript slides
Clojurescript slidesClojurescript slides
Clojurescript slides
 
Why you should be excited about ClojureScript
Why you should be excited about ClojureScriptWhy you should be excited about ClojureScript
Why you should be excited about ClojureScript
 
Functional Programming with Immutable Data Structures
Functional Programming with Immutable Data StructuresFunctional Programming with Immutable Data Structures
Functional Programming with Immutable Data Structures
 
Nomenclatura e peças de container
Nomenclatura  e peças de containerNomenclatura  e peças de container
Nomenclatura e peças de container
 
Geometria Projetiva
Geometria ProjetivaGeometria Projetiva
Geometria Projetiva
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
Javascript Libraries
Javascript LibrariesJavascript Libraries
Javascript Libraries
 
How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!How to Make an Eight Bit Computer and Save the World!
How to Make an Eight Bit Computer and Save the World!
 
Ragel talk
Ragel talkRagel talk
Ragel talk
 
A Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the WebA Practical Guide to Connecting Hardware to the Web
A Practical Guide to Connecting Hardware to the Web
 
Introdução ao Arduino
Introdução ao ArduinoIntrodução ao Arduino
Introdução ao Arduino
 
Minicurso arduino
Minicurso arduinoMinicurso arduino
Minicurso arduino
 
Incanter Data Sorcery
Incanter Data SorceryIncanter Data Sorcery
Incanter Data Sorcery
 
Rango
RangoRango
Rango
 
Fab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine DesignFab.in.a.box - Fab Academy: Machine Design
Fab.in.a.box - Fab Academy: Machine Design
 
The Digital Revolution: Machines that makes
The Digital Revolution: Machines that makesThe Digital Revolution: Machines that makes
The Digital Revolution: Machines that makes
 
Hadoop + Clojure
Hadoop + ClojureHadoop + Clojure
Hadoop + Clojure
 
Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.Hadoop - Simple. Scalable.
Hadoop - Simple. Scalable.
 
Hadoop and Hive Development at Facebook
Hadoop and Hive Development at FacebookHadoop and Hive Development at Facebook
Hadoop and Hive Development at Facebook
 
Multi-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case StudyMulti-core Parallelization in Clojure - a Case Study
Multi-core Parallelization in Clojure - a Case Study
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Recently uploaded (20)

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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
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
 
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...
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
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
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
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
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
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
 

JPA and Hibernate

  • 1. JPA and Hibernate Mike Calvo mike@citronellasoftware.com
  • 2. What is JPA? • Java Persistence API • A specification for generic ORM – Not an implementation – Vendor-neutral • Based on Annotations – Metadata • Developed out of EJB 3 Specification – Replacement for train wreck EJB 2 persistence – Stand alone specification (does not require JEE container)
  • 3. What is Hibernate? • Very popular open source Java ORM tool • Originally developed by Gavin King • Now maintained by Redhat (JBoss Group) • Implements JPA specification • Predates JPA – Has its own custom API for persisting mapped objects
  • 4. Choosing an API • JPA Benefits – Standard – Vendor-neutral – Works with EJB 3 • Hibernate Benefits – More mature (fully developed) – Works with Java 1.4 and older • My Policy – Use JPA when you can – Use Hibernate API when you need it
  • 5. Enabling Hibernate & JPA with Maven <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate</artifactId> <version>3.2.5.ga</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId> <version>3.3.0.ga</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-entitymanager</artifactId> <version>3.3.1.ga</version> </dependency>
  • 6. Configuring Mapping • Hibernate legacy – XML configuration files – Each file mapped a class and it’s persistent fields • JPA and Hibernate 3.2 and above – Annotations (javax.persistence package) – Class-level: marks a class as persistent – Method/File level: configure field and relationship persistence • Hibernate still supports XML configuration
  • 7. Core JPA Annotations • @Entity • @Id • @GeneratedValue • @Column • @JoinColumn • @OneToMany • @ManyToOne • @ManyToMany
  • 8. JPA Annotation Rules • Any persistent class must be annotated with @Entity (or inherit from a class that does) • All persistent classes must have a field annotated by @Id signifying the primary key • All instance fields in a persistent class are assumed to be mapped to columns with the same name as the field – @Transient will remove a field from mapping • Relationships are not automatically mapped – Relationships are modeled as aggregate members – Require an @OneToMany, @ManyToOne, or @ManyToMany
  • 9. Overriding Defaults • Class annotation @Table defines specific table mappings – Name • Field annotation @Column defines specific column mappings – Name – Nullability – Size – Uniqueness
  • 10. Relationships • @OneToMany – Annotate a member variable which is an @Entity annotated type • @ManyToOne or @ManyToMany – Annotate a member variable which is a standard Java collection with parameter of type which is an @Entity – Type of collection is significant • Use @JoinColumn to define specifics about the join column
  • 11. Relationship Features • Lazy Loading and Fetch • Cascading • Fetch • Polymorphic
  • 12. Lazy Loading • Performance optimization • Related items are not retrieved until they are first accessed – Field level access • Limited to work only within the Session or EntityManager that loaded the parent object – Causes a big problem in web applications
  • 13. Fetch • Fetch mode – Lazy – Eager – disable lazy loading • Mode can be configured on each relationship • Consider performance and use when configuring fetch
  • 14. Cascade • Tells Hibernate whether to follow the path of the relationship on – Insert – Update – Delete – All • Hibernate adds options – Delete All Orphans
  • 15. Inheritance • JPA and Hibernate support mapping Class inheritance to relational tables • Three approaches provided: – Table per class hierarchy – Table per sub class – Table per concrete class
  • 16. Table per Class Hierarchy • All of the data representing the properties of every class in the Hierarchy are stored in one table • Requires that columns representing fields in subclasses allow null • Uses discriminator column to determine the type of object represented a row – Each subclass must declare the discriminator value for the type
  • 17. Table per Class Hierarchy Example • Patient and Physician extend Person
  • 19. Resultant DDL Has fields for both Patient and Physician
  • 20. Table per Subclass • Each subclass in the hierarchy gets its own table • Parent class fields are in one table • Primary key in subclass tables refer back to the parent class table • Use joined-subclass configuration
  • 21. Table per Subclass Example • CreditCardPayment, CashPayment, and CheckPayment all extend Payment
  • 24. Discriminator w/Table Per Subclass • Table per subclass also supports the use of a discriminator • Not required
  • 25. Table per Concrete Class • Each class in the hierarchy gets its own table • The parent class fields are duplicated in each table • Two approaches – Union subclass – Implicit polymorphism
  • 26. Union Subclass • Map the Parent class as normal – No discriminator required – Specify parent class properties – @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) • Map each of the subclasses – Specify a table name – Specify subclass properties
  • 27. Implicit Polymorphism • Parent class is not mapped using hibernate – Annotate with @MappedSuperclass • Each of the subclasses is mapped as a normal class – Map all of the properties, including the parent properties
  • 28. Implicit Polymorphism Example • Car and Truck extend Vehicle • SUV extends Truck
  • 29. Vehicle Parent Class • Class not mapped, but properties are
  • 32. Persistence Configuration Files • Used to define application persistence properties – Database connection information – Dialect (database-specific language) – Logging – Schema creation parameters • Default location is in CLASSPATH • JPA – META-INF/persistence.xml • Hibernate – hibernate.cfg.xml
  • 33. Example persistence.xml <persistence xmlns=quot;http://java.sun.com/xml/ns/persistencequot; xmlns:xsi=quot;http://www.w3.org/2001/XMLSchema-instancequot; xsi:schemaLocation=quot;http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsdquot; version=quot;1.0quot;> <persistence-unit name=“persistence-unitquot;> <properties> <property name=quot;dialectquot; value=quot;org.hibernate.dialect.DerbyDialectquot;/> <property name=quot;hibernate.hbm2ddl.autoquot; value=quot;updatequot;/> <property name=quot;hibernate.connection.driver_classquot; value=quot;org.apache.derby.jdbc.EmbeddedDriverquot;/> <property name=quot;hibernate.connection.url“ value=quot;jdbc:derby:db;create=truequot;/> <property name=quot;hibernate.connection.autocommitquot; value=quot;falsequot; /> </properties> </persistence-unit> </persistence>
  • 34. Persistence Core Classes • Hibernate – Configuration -> SessionFactory -> Session – Session is gateway to persistence functions • JPA – Persistence -> EntityManagerFactory -> EntityManager – EntityManager is gateway to persistence functions
  • 35. EntityManager Functionality • persist(Obect o) – Saves or updates the specified object tree • remove(Object o) – Deletes the specified object • find(Class type, Serializable id) – Retrieves the item of the specified type by id • merge(Object o) – Attaches a detached instance to the manager (required for update on item retrieved from a different manager) • getTransaction() – Provides a transaction object to perform commit and rollback functions
  • 36. Querying with JPA • JPAQL/HQL • Named Queries • Criteria • By Example • Native SQL
  • 37. JPAQL and HQL • Query languages that are similar to SQL but are more object-centric • Supports – Selection of object instances from persistent types – Selection of properties (rather than columns) – Polymorphic selection – Automatic joining for nested properties • Should be very comfortable for those familiar with SQL • JPAQL is a subset of HQL – Hibernate implementation will support both
  • 38. Example JPAQL/HQL “from Item i where i.name = ‘foobar’” “from Item i where i.bidder.name = ‘Mike’” <<< Implicit join “from Car c where c.coupe = true” “from Item i where i.bids is not empty” “from Item i where size(i.bids) > 3” <<< Implicit join “from Item i order by i.name asc, i.entryDate asc” “from Item i join i.bids b where b.amount > 100” <<< will return rows with an array “select distinct(i) from Item i join i.bids b where b.amount > 100” <<< returns Items “select i.name, i.description from Item i where entryDate > ?”
  • 39. More JPAQL/HQL Features • String functions – upper, lower, length, substring, concat, trim • Aggregation functions – count, min, max, sum, avg – Can require “group by” clause – Also supports “having” on “group by” • Subselects
  • 40. Query Parameters • Work just like JDBC Parameters – ? Will act as a placeholder for an indexed parameter – :name will designate a parameter with the name of “name” • Examples – select i from Item where name like ? – select i from Item where name like :name
  • 41. Running a JPAQL/HQL Query • Must be created from the EntityManager or Session – EntityManger.createQuery(String jpaql) – Session.createQuery(String hql) • Query objects can be configured – Maximum number of results – Parameters set • Query objects can then be used to list out the results of the query – list() returns a java.util.List
  • 42. Named Queries • Predefined queries that can be executed by name – Standard QL used for query • Defined using @NamedQuery – Typically above the persistent class the query is for – Defined with name and query values • Running the query – EntityManager.createNamedQuery(name) – Session.getNamedQuery(name)
  • 43. Criteria and Example Queries • Hibernate only feature • Full API for programmatically defining the query structure using objects • Created by Session • Criteria maps all logical restrictions to a query as objects and methods • Example query uses an example object as the basis to find other objects – Based on Criteria API
  • 44. Native SQL Queries • Both JPA and Hibernate support running raw SQL – Session.createSQLQuery(sql) – EntityManager.createNativeQuery(sql) • Supports specifying the entity type to convert the results to
  • 45. Embeddable Objects • Some classes contain persistent data, but are not true entities – Think Data Objects in DDD • JPA supports this with @Embeddable – Annotate your embeddable class • When your entity needs to store the fields of an embeddable class, include an instance of that type as a property and annotate it with @Embedded
  • 46. Custom Types • Sometimes you don’t want the default mapping Hibernateassociates with your property • Reasons – Combine two fields into one column – Numbers and dates stored as strings – Data encryption
  • 47. Creating a UserType • Implement the org.hibernate.usertype.UserType interface • returnedClass() – Tells Hibernate what type of value to expect for your Type • sqlTypes() – Tells Hibernate what JDBC types you are mapping to • Key conversion methods – nullSafeGet – nullSafeSet – Have access to • JDBC resultSet • Column names for property • Owning object
  • 48. Example UserType • DateAsStringUserType converts dates to Strings formatted as yyyy-MM-dd
  • 49. Other UserType Methods • equals and hashcode – Make sure you check for nulls • isMutable – Are objects of the returned type mutable (Strings are not) • assemble and disassemble – Prepare for/extract from caching – Strings can be cached as is (simply return) • replace – Handles a merge – Return the first parameter on immutable items