SlideShare a Scribd company logo
1 of 31
Working with JPA
Lecturer: Ondrej Mihályi
Contents
●JPA entities and persistence units
●Mapping of JPA entities to SQL database
●Querying entities
●Lazy and eager loading
●Id generation
●Optimistic locking
JPA entities
●An entity is a lightweight persistence domain object
●Typically, an entity represents a table in a relational
database, and each entity instance corresponds to a
row in that table
●fields or properties use object/relational mapping
annotations to map the entities and entity
relationships to the relational data
Requirements for Entity Classes
●javax.persistence.Entity annotation
●Constructor without arguments
●Persistent values properties/fields may be of:
l
Java primitive values, their wrappers and String
l
Other Java standard number or datetime types
l
Enums, byta and char arrays
l
Other entities, collections of entities, embeddable
classes
Entity persistence type
●Persistent Fields
l
Mapped Fields are accessed directly
●Persistent Properties
l
Properties mapped via getter method accessed via
setter/getter according to Java Beans convention
●Transient fields/properties
l
marked by transient or @Transient
l
their state is not saved to database
Validating integrity of JPA entities
●Annotations of Java Bean Validation may be
used to ensure integrity before committing
transaction
l
javax.validation.constraints package
●Most used constraints:
l
@NotNull, @Pattern, @Past
Persistence Unit
●Persistence is turned on by presence of valid
persistence.xml in META-INF directory
●persistence.xml defines groups of entities together
with connection parameters
●Persistence unit represents a database
●Persistence context is tied to a persistence unit and
represents a single connection to the database
Types of definition of connection
information
●Transaction-type
l
JTA – datasource to the DB and transaction are
configured and handled by the application server –
the datasource is provided by specified JNDI name
in element jta-data-source
l
RESOURCE_LOCAL – connection information is
specified directly and transactions are controlled by
calling of appropriate methods
Entity Manager
●Component that represents single connection
●API to control persistence context of JPA entities,
search JPA entities and provide means to query DB
and execute batch statements
●Entity Manager Factory
l
Represents information to reate connetions
l
Can be used to create Entity Managers
l
Provides information about database metadata
Lifecycle of a JPA entity
●to be
synchronized
with a DB, entity
must be
attached to an
Entity Manager
Mapping of entities
●Entity must be included in a persistence-unit
●Annotated by @Entity
●Must have a primary key specified
●All fields/properties of an entity are mapped to DB
l
Unless marked as transient or with @Transient
annotation
●Name of columns in DB are inferred from
field/property names
Mapping of entities – primitive types
●Primitive types are automatically mapped to a
column of appropriate SQL type
l
String to VARCHAR
l
Numbers to NUMERIC, DECIMAL, …
l
Boolean to BOOLEAN, NUMERIC
●To refine mapping, additional JPA annotations are
needed (@Lob, @Column)
Mapping of entities – date and time
●Mapping of Date and Calendar
●Needs annotation Temporal, with definition of
type of data:
l
DATE
l
TIME
l
TIMESTAMP
Mapping of entities – enumerations
●Need to use @Enumerated
●Two options how to map to DB:
l
ORDINAL – not stable enum values are
added/removed
l
STRING – not very convenient, if we want to
map by id or to an existing enumeration table
Mapping of entities – collections
●According to direction
l
Uni-directional vs. Bi-directional
●According to cardinality
l
@OneToOne
l
@OneToMany
l
@ManyToOne
l
@ManyToMany (intermediary table is generated)
Mapping of entities – bi-directional
relations
●Only one direction is mapped to a column
l
@JoinColumn overwrites default mapping
●Reverse direction is mapped to a Java field in the
other entity
●In case of OneToOne and ManyToMany, annotations
on both references
●Otherwise OneToMany is in one entity, ManyToOne
in the other entity
Mapping of entities – collections of
primitive types
●Need to use @ElementCollection
●A separate table to hold values of collection is
generated
Mapping of entities – difference
between collection types
Collection type Description
List Ordered list of elements. Order is either not persisted, or
defined by additional integer column in DB. Only unique
elements are stored in DB.
Set Unordered collection of elements. Ensures that elements are
unique. Very close to how data is stored in DB.
Collection Similar to List, but can be represented also by a Set
Map Essentially a Set of keys with attached values, not much
used in practice
Customization of DB mapping
●JPA listeners
●
@PrePersist, @PreRemove, @PostPersist,
@PostRemove, @PreUpdate,
@PostUpdate, @PostLoad
Customization of DB mapping
●Converters – new in Java EE 7
l
@Convert to specify converter class
l
Converter class implements
AttributeConverter
l
Converter class must be mentioned in
orm.xml
Queries
●Two standard ways:
l
JPQL – text-based queries similar to SQL
l
Criteria – Java object based queries with
syntax check and strict typing
●Also possible to execute a direct SQL query
JPQL
●SELECT b FROM Book b WHERE b.name like
'%Web%'
l
Instead of table we use name of Java class
l
We assign alias to the entity to reference it
l
We may return both primitive types and complete
entities (by the reference)
l
We may compare entities (their id will be compared)
l
We may access fields and make joins by dot notation
JPQL – named queries
●Queries tied with a JPA entity using @NamedQuery
annotation
●Compiled and checked at application deployment
●Executed by a name
●Name of a named query must be unique in the whole
persistence unit, not only within the entity
JPQL – joins
●Joins are created when dot notation is used:
l
SELECT b.tags FROM Book b WHERE b.id = 2
●When we need to reference properties of the joined
entities, we must explicitely join them:
l
SELECT DISTINCT t.name FROM Book b INNER
JOIN b.tags t
l
Only mapped properties can be joined
Criteria API
●Criteria queries are written using Java APIs, are
typesafe, and are portable
●However, too much of complex code needs for even
simple queries
●Libraries exist to simplify working with criteria
●Criteria API is convenient to build dynamic queries
based on parameters (for search dialogs, filters, ...)
Lazy loading
● Simple types are loaded from DB at the time when entity is loaded
(EAGER)
● Collections are loaded only when a method on a collection is
executed (LAZY)
l
Only reference to a proxy collection is injected to the entity
● This behavior can be changed by FetchType attribute on collection
annotations
● When lazy collection is accessed when entity was disconnected from
transaction, LazyLoadingException is thrown
Lazy loading behavior
●Default fetch behavior can be changed by
FetchType attribute on collection annotations
●Lazy references can be loaded eagerly in
JPQL by fetch join
Lazy loading problems
●When lazy collection is accessed when entity
was disconnected from transaction,
LazyLoadingException is thrown
●There are various strategies to avoid this:
l
Data Transfer Objects, Extended Persistence
Context, ...
Id generation for primary key
●an attribute of type long or String is marked with @Id
●Strategies to generate Id values:
l
IDENTITY – id generation by the DB
l
SEQUENCE – generation of id from a sequence
l
TABLE – emulates SEQUENCE using a table
l
AUTO – JPA provider will choose according to what
is supported by the DB
Optimistic locking
●Technique to prevent conflicts without using DB
locking mechanism
l
DB locks are often too restrictive, slow down the
DB, may cause deadlocks
●Each row of a table stores its version number
●When JPA finds out that the transaction is trying to
modify an entity with older version than in DB, it
detects conflict and throws an exception with rollback
Optimistic locking – version attribute
●@Version marks entity property, which is mapped to
the version column
●Version number is updated and used by JPA
automatically

More Related Content

What's hot

Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsEmiel Paasschens
 
Java Training in Noida Delhi NCR BY Ducat
Java Training in Noida Delhi NCR BY DucatJava Training in Noida Delhi NCR BY Ducat
Java Training in Noida Delhi NCR BY DucatShri Prakash Pandey
 
Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Fresherszynofustechnology
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6...WebStackAcademy
 
ADA programming language
ADA programming languageADA programming language
ADA programming languageAisha Kalsoom
 
Oracle Course content
Oracle Course contentOracle Course content
Oracle Course contentTRINADH G
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variablesPushpendra Tyagi
 
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages Charitha Gamage
 
Functions in sap hana
Functions in sap hanaFunctions in sap hana
Functions in sap hanakabilarasan R
 
A Learning to Rank Project on a Daily Song Ranking Problem
A Learning to Rank Project on a Daily Song Ranking ProblemA Learning to Rank Project on a Daily Song Ranking Problem
A Learning to Rank Project on a Daily Song Ranking ProblemSease
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptRangana Sampath
 
Tool Development 05 - XML Schema, INI, JSON, YAML
Tool Development 05 - XML Schema, INI, JSON, YAMLTool Development 05 - XML Schema, INI, JSON, YAML
Tool Development 05 - XML Schema, INI, JSON, YAMLNick Pruehs
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers GuideDaisyWatson5
 
Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design PatternsNLJUG
 
Tool Development 04 - XML
Tool Development 04 - XMLTool Development 04 - XML
Tool Development 04 - XMLNick Pruehs
 
Haystack London - Search Quality Evaluation, Tools and Techniques
Haystack London - Search Quality Evaluation, Tools and Techniques Haystack London - Search Quality Evaluation, Tools and Techniques
Haystack London - Search Quality Evaluation, Tools and Techniques Andrea Gazzarini
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional ProgrammingAapo Kyrölä
 
Introduction to Erlang Programming Language
Introduction to Erlang Programming LanguageIntroduction to Erlang Programming Language
Introduction to Erlang Programming LanguageYasas Gunarathne
 

What's hot (20)

Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and StreamsIntroduction of Java 8 with emphasis on Lambda Expressions and Streams
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
 
Java Training in Noida Delhi NCR BY Ducat
Java Training in Noida Delhi NCR BY DucatJava Training in Noida Delhi NCR BY Ducat
Java Training in Noida Delhi NCR BY Ducat
 
Java Interview Questions For Freshers
Java Interview Questions For FreshersJava Interview Questions For Freshers
Java Interview Questions For Freshers
 
Insight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FPInsight into java 1.8, OOP VS FP
Insight into java 1.8, OOP VS FP
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 6...
 
ADA programming language
ADA programming languageADA programming language
ADA programming language
 
Oracle Course content
Oracle Course contentOracle Course content
Oracle Course content
 
Java basics and java variables
Java basics and java variablesJava basics and java variables
Java basics and java variables
 
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
Evaluate And Analysis of ALGOL, ADA ,PASCAL Programming Languages
 
Functions in sap hana
Functions in sap hanaFunctions in sap hana
Functions in sap hana
 
A Learning to Rank Project on a Daily Song Ranking Problem
A Learning to Rank Project on a Daily Song Ranking ProblemA Learning to Rank Project on a Daily Song Ranking Problem
A Learning to Rank Project on a Daily Song Ranking Problem
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Tool Development 05 - XML Schema, INI, JSON, YAML
Tool Development 05 - XML Schema, INI, JSON, YAMLTool Development 05 - XML Schema, INI, JSON, YAML
Tool Development 05 - XML Schema, INI, JSON, YAML
 
Java Interview Questions Answers Guide
Java Interview Questions Answers GuideJava Interview Questions Answers Guide
Java Interview Questions Answers Guide
 
Real-World Scala Design Patterns
Real-World Scala Design PatternsReal-World Scala Design Patterns
Real-World Scala Design Patterns
 
Lambdas
LambdasLambdas
Lambdas
 
Tool Development 04 - XML
Tool Development 04 - XMLTool Development 04 - XML
Tool Development 04 - XML
 
Haystack London - Search Quality Evaluation, Tools and Techniques
Haystack London - Search Quality Evaluation, Tools and Techniques Haystack London - Search Quality Evaluation, Tools and Techniques
Haystack London - Search Quality Evaluation, Tools and Techniques
 
About Functional Programming
About Functional ProgrammingAbout Functional Programming
About Functional Programming
 
Introduction to Erlang Programming Language
Introduction to Erlang Programming LanguageIntroduction to Erlang Programming Language
Introduction to Erlang Programming Language
 

Viewers also liked

JPQL/ JPA Activity 1
JPQL/ JPA Activity 1JPQL/ JPA Activity 1
JPQL/ JPA Activity 1SFI
 
JPQL/ JPA Activity 2
JPQL/ JPA Activity 2JPQL/ JPA Activity 2
JPQL/ JPA Activity 2SFI
 
JPQL/ JPA Activity 3
JPQL/ JPA  Activity 3JPQL/ JPA  Activity 3
JPQL/ JPA Activity 3SFI
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernatepatinijava
 
Web Services Part 2
Web Services Part 2Web Services Part 2
Web Services Part 2patinijava
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsOndrej Mihályi
 
Introduction to developing modern web apps
Introduction to developing modern web appsIntroduction to developing modern web apps
Introduction to developing modern web appsFabricio Epaminondas
 
Quickstart for continuous integration
Quickstart for continuous integrationQuickstart for continuous integration
Quickstart for continuous integrationFabricio Epaminondas
 
Continuous integration practices to improve the software quality
Continuous integration practices to improve the software qualityContinuous integration practices to improve the software quality
Continuous integration practices to improve the software qualityFabricio Epaminondas
 
FinelyMe-JustFit Intro
FinelyMe-JustFit IntroFinelyMe-JustFit Intro
FinelyMe-JustFit IntroCheng Ta Yeh
 
Web Services Part 1
Web Services Part 1Web Services Part 1
Web Services Part 1patinijava
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transactionpatinijava
 
Continuous testing in agile projects 2015
Continuous testing in agile projects 2015Continuous testing in agile projects 2015
Continuous testing in agile projects 2015Fabricio Epaminondas
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Introduction To Spring
Introduction To SpringIntroduction To Spring
Introduction To SpringIlio Catallo
 

Viewers also liked (20)

JPQL/ JPA Activity 1
JPQL/ JPA Activity 1JPQL/ JPA Activity 1
JPQL/ JPA Activity 1
 
JPQL/ JPA Activity 2
JPQL/ JPA Activity 2JPQL/ JPA Activity 2
JPQL/ JPA Activity 2
 
JPQL/ JPA Activity 3
JPQL/ JPA  Activity 3JPQL/ JPA  Activity 3
JPQL/ JPA Activity 3
 
Ejb5
Ejb5Ejb5
Ejb5
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
 
15 jpaql
15 jpaql15 jpaql
15 jpaql
 
15 jpa
15 jpa15 jpa
15 jpa
 
Web Services Part 2
Web Services Part 2Web Services Part 2
Web Services Part 2
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applications
 
Introduction to developing modern web apps
Introduction to developing modern web appsIntroduction to developing modern web apps
Introduction to developing modern web apps
 
Quickstart for continuous integration
Quickstart for continuous integrationQuickstart for continuous integration
Quickstart for continuous integration
 
Continuous integration practices to improve the software quality
Continuous integration practices to improve the software qualityContinuous integration practices to improve the software quality
Continuous integration practices to improve the software quality
 
FinelyMe-JustFit Intro
FinelyMe-JustFit IntroFinelyMe-JustFit Intro
FinelyMe-JustFit Intro
 
Web Services Part 1
Web Services Part 1Web Services Part 1
Web Services Part 1
 
Designing Scalable Applications
Designing Scalable ApplicationsDesigning Scalable Applications
Designing Scalable Applications
 
Spring Transaction
Spring TransactionSpring Transaction
Spring Transaction
 
Continuous testing in agile projects 2015
Continuous testing in agile projects 2015Continuous testing in agile projects 2015
Continuous testing in agile projects 2015
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Introduction To Spring
Introduction To SpringIntroduction To Spring
Introduction To Spring
 

Similar to Working with jpa

Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Fahad Golra
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteTushar B Kute
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaArun Gupta
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Advance java session 14
Advance java session 14Advance java session 14
Advance java session 14Smita B Kumar
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalystdatamantra
 
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
 
Javatraining
JavatrainingJavatraining
Javatrainingducat1989
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternNitin Bhide
 
chapter-1-review-of-python-basics-copy.pdf
chapter-1-review-of-python-basics-copy.pdfchapter-1-review-of-python-basics-copy.pdf
chapter-1-review-of-python-basics-copy.pdfSangeethManojKumar
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/HibernateSunghyouk Bae
 
2008.07.17 발표
2008.07.17 발표2008.07.17 발표
2008.07.17 발표Sunjoo Park
 
GDSC Web Bootcamp - Day - 2 - JavaScript
GDSC Web Bootcamp -  Day - 2   - JavaScriptGDSC Web Bootcamp -  Day - 2   - JavaScript
GDSC Web Bootcamp - Day - 2 - JavaScriptSahithiGurlinka
 

Similar to Working with jpa (20)

Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2Lecture 9 - Java Persistence, JPA 2
Lecture 9 - Java Persistence, JPA 2
 
Jpa
JpaJpa
Jpa
 
Chapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B KuteChapter 01 Introduction to Java by Tushar B Kute
Chapter 01 Introduction to Java by Tushar B Kute
 
NHibernate
NHibernateNHibernate
NHibernate
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 IndiaUsing the latest Java Persistence API 2 Features - Tech Days 2010 India
Using the latest Java Persistence API 2 Features - Tech Days 2010 India
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
React-Native Lecture 11: In App Storage
React-Native Lecture 11: In App StorageReact-Native Lecture 11: In App Storage
React-Native Lecture 11: In App Storage
 
JavaEE Spring Seam
JavaEE Spring SeamJavaEE Spring Seam
JavaEE Spring Seam
 
Introducing Datawave
Introducing DatawaveIntroducing Datawave
Introducing Datawave
 
Advance java session 14
Advance java session 14Advance java session 14
Advance java session 14
 
Anatomy of spark catalyst
Anatomy of spark catalystAnatomy of spark catalyst
Anatomy of spark catalyst
 
NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)NHibernate (The ORM For .NET Platform)
NHibernate (The ORM For .NET Platform)
 
Javatraining
JavatrainingJavatraining
Javatraining
 
Iterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design patternIterator - a powerful but underappreciated design pattern
Iterator - a powerful but underappreciated design pattern
 
Data types in java
Data types in javaData types in java
Data types in java
 
chapter-1-review-of-python-basics-copy.pdf
chapter-1-review-of-python-basics-copy.pdfchapter-1-review-of-python-basics-copy.pdf
chapter-1-review-of-python-basics-copy.pdf
 
Alternatives of JPA/Hibernate
Alternatives of JPA/HibernateAlternatives of JPA/Hibernate
Alternatives of JPA/Hibernate
 
2008.07.17 발표
2008.07.17 발표2008.07.17 발표
2008.07.17 발표
 
GDSC Web Bootcamp - Day - 2 - JavaScript
GDSC Web Bootcamp -  Day - 2   - JavaScriptGDSC Web Bootcamp -  Day - 2   - JavaScript
GDSC Web Bootcamp - Day - 2 - JavaScript
 

More from Ondrej Mihályi

Easily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsEasily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsOndrej Mihályi
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroOndrej Mihályi
 
Bed con - MicroProfile: A Quest for a lightweight and reactive Enterprise Ja...
Bed con - MicroProfile:  A Quest for a lightweight and reactive Enterprise Ja...Bed con - MicroProfile:  A Quest for a lightweight and reactive Enterprise Ja...
Bed con - MicroProfile: A Quest for a lightweight and reactive Enterprise Ja...Ondrej Mihályi
 
Easily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsEasily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsOndrej Mihályi
 
How to bake_reactive_behavior_into_your_java_ee_applications
How to bake_reactive_behavior_into_your_java_ee_applicationsHow to bake_reactive_behavior_into_your_java_ee_applications
How to bake_reactive_behavior_into_your_java_ee_applicationsOndrej Mihályi
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsOndrej Mihályi
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsOndrej Mihályi
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsOndrej Mihályi
 
Business layer and transactions
Business layer and transactionsBusiness layer and transactions
Business layer and transactionsOndrej Mihályi
 
Maven in Java EE project
Maven in Java EE projectMaven in Java EE project
Maven in Java EE projectOndrej Mihályi
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introductionOndrej Mihályi
 

More from Ondrej Mihályi (11)

Easily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsEasily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data grids
 
Elastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara MicroElastic and Cloud-ready Applications with Payara Micro
Elastic and Cloud-ready Applications with Payara Micro
 
Bed con - MicroProfile: A Quest for a lightweight and reactive Enterprise Ja...
Bed con - MicroProfile:  A Quest for a lightweight and reactive Enterprise Ja...Bed con - MicroProfile:  A Quest for a lightweight and reactive Enterprise Ja...
Bed con - MicroProfile: A Quest for a lightweight and reactive Enterprise Ja...
 
Easily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data gridsEasily scale enterprise applications using distributed data grids
Easily scale enterprise applications using distributed data grids
 
How to bake_reactive_behavior_into_your_java_ee_applications
How to bake_reactive_behavior_into_your_java_ee_applicationsHow to bake_reactive_behavior_into_your_java_ee_applications
How to bake_reactive_behavior_into_your_java_ee_applications
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applications
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applications
 
How to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applicationsHow to bake reactive behavior into your Java EE applications
How to bake reactive behavior into your Java EE applications
 
Business layer and transactions
Business layer and transactionsBusiness layer and transactions
Business layer and transactions
 
Maven in Java EE project
Maven in Java EE projectMaven in Java EE project
Maven in Java EE project
 
Java EE web project introduction
Java EE web project introductionJava EE web project introduction
Java EE web project introduction
 

Recently uploaded

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 

Recently uploaded (20)

How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 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
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 

Working with jpa

  • 1. Working with JPA Lecturer: Ondrej Mihályi
  • 2. Contents ●JPA entities and persistence units ●Mapping of JPA entities to SQL database ●Querying entities ●Lazy and eager loading ●Id generation ●Optimistic locking
  • 3. JPA entities ●An entity is a lightweight persistence domain object ●Typically, an entity represents a table in a relational database, and each entity instance corresponds to a row in that table ●fields or properties use object/relational mapping annotations to map the entities and entity relationships to the relational data
  • 4. Requirements for Entity Classes ●javax.persistence.Entity annotation ●Constructor without arguments ●Persistent values properties/fields may be of: l Java primitive values, their wrappers and String l Other Java standard number or datetime types l Enums, byta and char arrays l Other entities, collections of entities, embeddable classes
  • 5. Entity persistence type ●Persistent Fields l Mapped Fields are accessed directly ●Persistent Properties l Properties mapped via getter method accessed via setter/getter according to Java Beans convention ●Transient fields/properties l marked by transient or @Transient l their state is not saved to database
  • 6. Validating integrity of JPA entities ●Annotations of Java Bean Validation may be used to ensure integrity before committing transaction l javax.validation.constraints package ●Most used constraints: l @NotNull, @Pattern, @Past
  • 7. Persistence Unit ●Persistence is turned on by presence of valid persistence.xml in META-INF directory ●persistence.xml defines groups of entities together with connection parameters ●Persistence unit represents a database ●Persistence context is tied to a persistence unit and represents a single connection to the database
  • 8. Types of definition of connection information ●Transaction-type l JTA – datasource to the DB and transaction are configured and handled by the application server – the datasource is provided by specified JNDI name in element jta-data-source l RESOURCE_LOCAL – connection information is specified directly and transactions are controlled by calling of appropriate methods
  • 9. Entity Manager ●Component that represents single connection ●API to control persistence context of JPA entities, search JPA entities and provide means to query DB and execute batch statements ●Entity Manager Factory l Represents information to reate connetions l Can be used to create Entity Managers l Provides information about database metadata
  • 10. Lifecycle of a JPA entity ●to be synchronized with a DB, entity must be attached to an Entity Manager
  • 11. Mapping of entities ●Entity must be included in a persistence-unit ●Annotated by @Entity ●Must have a primary key specified ●All fields/properties of an entity are mapped to DB l Unless marked as transient or with @Transient annotation ●Name of columns in DB are inferred from field/property names
  • 12. Mapping of entities – primitive types ●Primitive types are automatically mapped to a column of appropriate SQL type l String to VARCHAR l Numbers to NUMERIC, DECIMAL, … l Boolean to BOOLEAN, NUMERIC ●To refine mapping, additional JPA annotations are needed (@Lob, @Column)
  • 13. Mapping of entities – date and time ●Mapping of Date and Calendar ●Needs annotation Temporal, with definition of type of data: l DATE l TIME l TIMESTAMP
  • 14. Mapping of entities – enumerations ●Need to use @Enumerated ●Two options how to map to DB: l ORDINAL – not stable enum values are added/removed l STRING – not very convenient, if we want to map by id or to an existing enumeration table
  • 15. Mapping of entities – collections ●According to direction l Uni-directional vs. Bi-directional ●According to cardinality l @OneToOne l @OneToMany l @ManyToOne l @ManyToMany (intermediary table is generated)
  • 16. Mapping of entities – bi-directional relations ●Only one direction is mapped to a column l @JoinColumn overwrites default mapping ●Reverse direction is mapped to a Java field in the other entity ●In case of OneToOne and ManyToMany, annotations on both references ●Otherwise OneToMany is in one entity, ManyToOne in the other entity
  • 17. Mapping of entities – collections of primitive types ●Need to use @ElementCollection ●A separate table to hold values of collection is generated
  • 18. Mapping of entities – difference between collection types Collection type Description List Ordered list of elements. Order is either not persisted, or defined by additional integer column in DB. Only unique elements are stored in DB. Set Unordered collection of elements. Ensures that elements are unique. Very close to how data is stored in DB. Collection Similar to List, but can be represented also by a Set Map Essentially a Set of keys with attached values, not much used in practice
  • 19. Customization of DB mapping ●JPA listeners ● @PrePersist, @PreRemove, @PostPersist, @PostRemove, @PreUpdate, @PostUpdate, @PostLoad
  • 20. Customization of DB mapping ●Converters – new in Java EE 7 l @Convert to specify converter class l Converter class implements AttributeConverter l Converter class must be mentioned in orm.xml
  • 21. Queries ●Two standard ways: l JPQL – text-based queries similar to SQL l Criteria – Java object based queries with syntax check and strict typing ●Also possible to execute a direct SQL query
  • 22. JPQL ●SELECT b FROM Book b WHERE b.name like '%Web%' l Instead of table we use name of Java class l We assign alias to the entity to reference it l We may return both primitive types and complete entities (by the reference) l We may compare entities (their id will be compared) l We may access fields and make joins by dot notation
  • 23. JPQL – named queries ●Queries tied with a JPA entity using @NamedQuery annotation ●Compiled and checked at application deployment ●Executed by a name ●Name of a named query must be unique in the whole persistence unit, not only within the entity
  • 24. JPQL – joins ●Joins are created when dot notation is used: l SELECT b.tags FROM Book b WHERE b.id = 2 ●When we need to reference properties of the joined entities, we must explicitely join them: l SELECT DISTINCT t.name FROM Book b INNER JOIN b.tags t l Only mapped properties can be joined
  • 25. Criteria API ●Criteria queries are written using Java APIs, are typesafe, and are portable ●However, too much of complex code needs for even simple queries ●Libraries exist to simplify working with criteria ●Criteria API is convenient to build dynamic queries based on parameters (for search dialogs, filters, ...)
  • 26. Lazy loading ● Simple types are loaded from DB at the time when entity is loaded (EAGER) ● Collections are loaded only when a method on a collection is executed (LAZY) l Only reference to a proxy collection is injected to the entity ● This behavior can be changed by FetchType attribute on collection annotations ● When lazy collection is accessed when entity was disconnected from transaction, LazyLoadingException is thrown
  • 27. Lazy loading behavior ●Default fetch behavior can be changed by FetchType attribute on collection annotations ●Lazy references can be loaded eagerly in JPQL by fetch join
  • 28. Lazy loading problems ●When lazy collection is accessed when entity was disconnected from transaction, LazyLoadingException is thrown ●There are various strategies to avoid this: l Data Transfer Objects, Extended Persistence Context, ...
  • 29. Id generation for primary key ●an attribute of type long or String is marked with @Id ●Strategies to generate Id values: l IDENTITY – id generation by the DB l SEQUENCE – generation of id from a sequence l TABLE – emulates SEQUENCE using a table l AUTO – JPA provider will choose according to what is supported by the DB
  • 30. Optimistic locking ●Technique to prevent conflicts without using DB locking mechanism l DB locks are often too restrictive, slow down the DB, may cause deadlocks ●Each row of a table stores its version number ●When JPA finds out that the transaction is trying to modify an entity with older version than in DB, it detects conflict and throws an exception with rollback
  • 31. Optimistic locking – version attribute ●@Version marks entity property, which is mapped to the version column ●Version number is updated and used by JPA automatically

Editor's Notes

  1. http://java.dzone.com/articles/mapping-enums-done-right
  2. http://java.dzone.com/articles/mapping-enums-done-right
  3. http://java.dzone.com/articles/mapping-enums-done-right