SlideShare une entreprise Scribd logo
1  sur  56
Télécharger pour lire hors ligne
Java Persistence API
Agenda
- Overview
- OR Mapping and Entity Introduction
- Entity Manager
- Transactions
- Persistence Context
- Relationships
- Query Capabilities
- Criteria
So, what's the big deal ?
- Relational DB and Java are world apart
- JDBC
- Mandates manual marshaling
- SQL Queries are difficult to manage
- No compile time support
- Boiler plate
- Database portability
- EJB 2.1
- Beast
- Horrible to work with
- Need of the hour : Lightweight POJO framework
What we need to save the day ?
- Higher level abstraction above JDBC
- Provide object view of RDBMS resources
- Simple to configure
- Lightweight
- Unobtrusive
- Local, but Mobile
- Integration and Testability
- Above all, Fun to work with
JPA
- All of the items listed in prev slide and ...
- Feature rich - Spec is about 500+ pages
- More than one way to do, that way looks complex
- Can be used in JavaEE as well as JavaSE environments
- Wait, we do have alternatives
- Data Mapper
- Java Data Objects
- JDBC
History
- JPA 1.0 (2006)
- Part of EJB 3.0 Spec
- Start over (Leaving Legacy Entity framework)
- Leading ORM experts on the panel (Hibernate, TopLink, etc)
- JPA 2.0 (2009)
- Added significant amount of features to catch up with ORM vendors
- Criteria API
- Bean Validation
- Metamodel
- JPA 2.1 (2013)
- Converters
- Criteria Update/Delete
- Stored Procedures
Big Players
- Client
- JPA Spec API
- JPA implementation
- Hibernate
- EclipseLink (prev TopLink)
- Apache OpenJPA
- Database Driver
- DB
- App Level : <persistence-unit>
- DB location : JNDI or DB URL
- List of Entity classes
- JPA provider : Hibernate
- Each Entity Class
- Table name
- Column names
- Client that uses JPA API
Code / Configuration
Lab - 1 - Module Setup
- Step 1 : Create a git repo
- Step 2 : Create a maven module (all defaults)
- Step 3 : Git commit
- Step 4 : Add Dependencies
- Client (JUnit)
- JPA Spec API
- Hibernate Core
- Entity Manager
- Database driver jar
- Step 5 : Add JPA configuration file : persistence.xml
- Step 6 : Assert em.isOpen()
- Step 7 : Git commit
OR Mapping
- Class <-> Table
- Property <-> Column
- Properties without mapping to any column : Transient
- Instance of Class <-> Row in the table
- Relies on Convention over Configuration
- Same old POJO underneath
- Entities are still EJBs ? Yes and No !
- Typically created with new operator
- Like SBs to container, Entities to EntityManager
- Resides on server but client directly interacts with them unlike EJB siblings
- Can define DB schema (not for production use)
Lab - 2 : Find Employee
- Step 1 : Employees Entity
- Step 2 : persistence.xml using MySQL Employees DB
- Step 3 : Assert employee presence
- Step 5 : Getters and Setters
- Step 6 : Updated test run
Object-Relational Mapping
- POJO needs something to become Entity
- 2 Ways : Annotations or XML
- Two types of Annotations
- Logical - Describes object model
- @Entity, @Basic, @Temporal etc.
- Physical - Describes physical schema
- @Table, @Column etc.
- Configuration by Exception
- Optional (Almost)
- Can be specified on Fields or Bean Properties
- Field annotations : Getters/Setters ignored
- Bare minimum : @Entity and @Id annotations
Mapping simple types
- Java Primitive types and Wrappers
- Byte[], Byte[], char[], Character[]
- java.lang.String
- java.math.BigInteger, BigDecimal
- java.util.Date, Calendar
- java.sql.Date, Time, Timestamp
- Enums
Entity, Who are you ?
- Entity must have an identity
- Annotate the field with @Id
- Equivalent of primary key
- Primary key not mandatory in DB table
- Multiple rows with same value in @Id mapped column. Trouble!
- Composite primary key
- @IdClass
- @EmbeddedId
- @MapsId
ID Generation
- 4 Types
- AUTO
- For prototyping only
- IDENTITY
- SEQUENCE
- TABLE
- DB agnostic
- IDENTITY and SEQUENCE need DB support
Serializable Entities
- Not mandated by Spec
- Application can opt for when
- Entities are shared across VMs
- Entities are stored in (clustered/serialized) sessions
Entity LIfecycle
Source
JPA Key Elements
Persistence
Source
EntityManagerFactory
Persistence
Context
Persistence Unit (Tangible)
- Named configuration of entity classes
EntityManager (Tangible)
- Central authority
- Qualifies simple POJOs into Entities
- Almost entire API is built in this one interface
- Provides API to
- Do CRUD
- Query
- Synchronize with Database
- Automatically sync to DB
- 1st Level Caching
- Works with JTA in server env
EntityManager (Tangible)
- Obtained from EntityManagerFactory
- Not thread-safe and must not be shared between threads
- Java EE
- Can be obtained directly using CDI injection or JNDI lookup
- Typically a transaction involves multiple components
- Need same entity context all through the transaction
- Multiple entity managers (within a tx) automatically points to same Persistence Context
- We don't have to pass reference of EntityManager between calls
- Java SE
- Using standalone bootstrap class Persistence
- Each call to emf.createEntityManager() creates a new isolated persistence context
Persistence Context (Intangible)
- Invisible
- A set of managed Entity objects
- Associated to a Persistence Unit
- Managed by one or more EntityManagers
- Only one Entity with same identity
- Entities contained within are “managed”
Source
Transaction
- ACID
- Transaction Demarcation : Act of beginning or completing
- JPA supports two types
- Resource Local
- JavaSE and JavaEE (without container support) applications
- Always application demarcated
- JTA
- aka Global Transactions
- Spans across resources (multiple DBs, Messaging server, etc…)
- Demarcated by containers (most of the times)
Transaction Contd...
- Transaction Synchronization : Process by which a persistence context is
registered with a transaction
- Transaction Association : Act of binding a persistence context to a transaction
- Transaction Propagation : Process of sharing a persistence context between
multiple entity managers within a transaction
Entity Manager Types
- EntityManager can be
- Container Managed Transaction-scoped
- Container Managed Extended
- Application scoped
- Scope is defined when the EntityManager is created
Container Managed Entity Manager
- Mostly we are talking about Java EE environment
- Injected via @PersistenceContext
- No need to Open or Close it
- Two flavors
- Transaction Scoped
- Extended
Transaction Scoped
- Default
- Lives as long as Transaction is alive
- Once transaction finished, all objects are detached
- Lazily created : When an operation on EntityManager is called
- @PersistenceContext hands over a proxy
- Stateless
- Maintenance free
Transaction Scoped Contd...
- Gets associated to the ongoing transaction seamlessly
Transaction Scoped Contd...
Extended Context
- Meant for @Stateful beans only
- Begins with EM creation and live till its closed
- Eagerly created : As soon as the txn begins
- The context gets destroyed when @Remove on SFSB is called
- Extended spans transactions and manages Entities between Txns
- Caching of Entity is not the objective but mostly you will be doing it
Extended Context
- Prevents Entities from becoming detached when txn ends
- Client can use bean fields to hold state and interact with DB
Extended Contd...
Application managed Context
- Mostly Java SE environments
- Can be used in Java EE Environment as well
- Application is responsible for context’s life cycle
- Extended by nature and spans multiple transactions
- Needs Explicit
- Creation : EntityManagerFactory.createEntityManager()
- Flushing/Closing : EntityManager.close()
- Is standalone and not propagated with transaction
- Can join transaction by EntityManager.joinTransaction()
- Typically used in Unit Testing
Recommendations
- Stateless Beans
- Preferred way to manage persistence operations
- Use @PersistantContext to inject EntityManager
- Stateful Beans
- Extended context
- State can include EntityContext and its result data
- Use JNDI lookup to get Stateful beans (no @Inject/@EJB)
- In case of rollback, DO NOT revive the detached object
Caching
- Concept is to avoid going to DB by maintaining an in-sync object in memory
- Entity Manager serves as 1st level cache
- Infinispan is default for WildFly
- Caching hurdles
- In memory objects are not transactional
- Data sync with Database
- Memory occupancy
Relationships in DB
- Achieved via
- Foreign Key
- Mapping tables
- Table with Foreign Key column is the owner
A bit insights into DB
Relationships
- No Entity is an Island!
- Table with foreign key always ends up with single association
- Roles
- Employee “works in” a Department
- Department “has” employees working in it
- One Entity can participate in many relationships
- Directionality
- Unidirectional
- BiDirectional
-
Relationships Cntd...
- Cardinality
- One to One
- One to Many
- Many to One
- Many to Many
- Ordinality (aka Optionality)
Relationships Myths
- Way to avoid business logic
- You still have to deal with CascadeType
- Gives flexibility
- Too little for too much price
- Lazy Vs Eager loading
- OpenEntityManagerInViewFilter
- Shields developer from database
- To very little extent
- Often the cause for killer bugs/defects
-
Single Valued Associations
- Cardinality of Target entity is 1
- ManyToOne
- OneToOne
- ManyToOne - Rules
- @JoinColumn goes in Entity that has foreign key defined
- @ManyToOne goes into the owning side i.e with foreign key
- @OneToMany(mappedBy) goes into the target Entity in case of Bidirectional
- OneToOne - Two Rules
- @JoinColumn goes in Entity that has foreign key defined
- @OneToOne(mappedBy) goes into the target Entity in case of Bidirectional
-
Many To One
- Always Source has has attribute of Target type
- Enables navigation from Source to Target
- @ManyToOne and @JoinColumn
- Table with foreign key is owning side
- Ownership is important because of foreign key column
- @JoinColumn is specified on the owning side
- Many to One mappings are always on owning side
Many To One
- @JoinColumn is optional
- Default join column : targetTable_targetIdColumn
- @Column won’t gel with these annotations
One To One
- Almost similar to Many To One
- @OneToOne and @JoinColumn
- Table with foreign key is the owning side
- @JoinColumn has to be on the side with foreign key
One To One Bidirectional
- Source Entity already has all the information
- It just needs which property on source entity has it
- @OneToOne(mappedBy)
Collection Valued Associations
- Source entity references one or more Target entities
- OneToMany
- ManyToMany
One To Many
- Nothing but Bidirectional ManyToOne
- Always implies a ManyToOne presence
- Always Bidirectional
- Always on the target side i.e. Not the Source side
- All configuration is in Source entity already
- Just needs the Source entity property information
- @OneToMany(mappedBy)
Many To Many
- @JoinColumn is not sufficient
- Can be achieved only by a join table
- Difficult to say who is the owner
- Either can be the owner
- The target side will have @ManyToMany(mappedBy)
- Absence of mappedBy will make them unidirectional
Many To Many Bidirectional
- mappedBy on the target side
- All it needs is the property configured in Source Entity
One To Many using a @TableJoin
- @OneToMany is not just bidirectional @ManyToOne
- Can be achieved with a @TableJoin
Lazy Relationships
- Not specified, @ManyToOne and @OneToOne guaranteed to Eagerly load
- Collection valued relationships by default is Lazily load
- Provider may choose to do Eager loading
Queries
- CRUD - Retrieval Rules
- As expected, constructed using EntityManager
- API
- Query
- TypedQuery
- Type
- Static - Annotation or XML
- Dynamic
- JPQL
- Criteria
- Dynamic queries are expensive
JPQL
- Limited yet powerful
- Metamodel is not mandatory (almost)
- Limited compile time safety
- Two types
- @NamedQuery
- Dynamic string query
Criteria API
- Programmatic control
- Robust
- Uses Objects instead of Strings
- Can result in bloated code
- More than One way to do it
- Query is prepared dynamically
- Allows flexible filtering
Criteria Query - Entity Result
References
- JPA 2.1 Specification (Not for humans)
- JPA 2.1 Java Doc (Amazingly small)
- (Blog) JPA 2.1 – 12 features every developer should know
- MySQL Employees Sample DB

Contenu connexe

Tendances

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Hibernate
HibernateHibernate
HibernateAjay K
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 
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 Hitesh-Java
 
Spring framework Introduction
Spring framework IntroductionSpring framework Introduction
Spring framework IntroductionAnuj Singh Rajput
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCFunnelll
 
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
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOPDzmitry Naskou
 

Tendances (20)

Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Java 8 lambda
Java 8 lambdaJava 8 lambda
Java 8 lambda
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Hibernate
HibernateHibernate
Hibernate
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
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
 
Spring framework Introduction
Spring framework IntroductionSpring framework Introduction
Spring framework Introduction
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Hibernate jpa
Hibernate jpaHibernate jpa
Hibernate jpa
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
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
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Spring Framework - AOP
Spring Framework - AOPSpring Framework - AOP
Spring Framework - AOP
 

En vedette

Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Patrycja Wegrzynowicz
 
Secure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EESecure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EEPatrycja Wegrzynowicz
 
Spring Boot. Boot up your development
Spring Boot. Boot up your developmentSpring Boot. Boot up your development
Spring Boot. Boot up your developmentStrannik_2013
 
Spring.Boot up your development
Spring.Boot up your developmentSpring.Boot up your development
Spring.Boot up your developmentStrannik_2013
 
Amazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarAmazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarCraig Dickson
 
Junior,middle,senior?
Junior,middle,senior?Junior,middle,senior?
Junior,middle,senior?Strannik_2013
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewCraig Dickson
 
Java persistence api
Java persistence api Java persistence api
Java persistence api Luis Goldster
 
Spring 4. Part 1 - IoC, AOP
Spring 4. Part 1 - IoC, AOPSpring 4. Part 1 - IoC, AOP
Spring 4. Part 1 - IoC, AOPNakraynikov Oleg
 
20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_ormKenan Sevindik
 

En vedette (20)

Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Hibernate using jpa
Hibernate using jpaHibernate using jpa
Hibernate using jpa
 
Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1Lazy vs. Eager Loading Strategies in JPA 2.1
Lazy vs. Eager Loading Strategies in JPA 2.1
 
Colloquium Report
Colloquium ReportColloquium Report
Colloquium Report
 
Secure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EESecure Authentication and Session Management in Java EE
Secure Authentication and Session Management in Java EE
 
Spring Boot. Boot up your development
Spring Boot. Boot up your developmentSpring Boot. Boot up your development
Spring Boot. Boot up your development
 
Second Level Cache in JPA Explained
Second Level Cache in JPA ExplainedSecond Level Cache in JPA Explained
Second Level Cache in JPA Explained
 
JPA - Beyond copy-paste
JPA - Beyond copy-pasteJPA - Beyond copy-paste
JPA - Beyond copy-paste
 
Spring.Boot up your development
Spring.Boot up your developmentSpring.Boot up your development
Spring.Boot up your development
 
Spring
SpringSpring
Spring
 
Spring Data Jpa
Spring Data JpaSpring Data Jpa
Spring Data Jpa
 
Amazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI WebinarAmazon Webservices for Java Developers - UCI Webinar
Amazon Webservices for Java Developers - UCI Webinar
 
Junior,middle,senior?
Junior,middle,senior?Junior,middle,senior?
Junior,middle,senior?
 
Introduction to JPA Framework
Introduction to JPA FrameworkIntroduction to JPA Framework
Introduction to JPA Framework
 
Java Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief OverviewJava Persistence API (JPA) - A Brief Overview
Java Persistence API (JPA) - A Brief Overview
 
Java persistence api
Java persistence api Java persistence api
Java persistence api
 
Gradle - Build System
Gradle - Build SystemGradle - Build System
Gradle - Build System
 
Spring 4. Part 1 - IoC, AOP
Spring 4. Part 1 - IoC, AOPSpring 4. Part 1 - IoC, AOP
Spring 4. Part 1 - IoC, AOP
 
20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm20160523 hibernate persistence_framework_and_orm
20160523 hibernate persistence_framework_and_orm
 
Java Persistence API
Java Persistence APIJava Persistence API
Java Persistence API
 

Similaire à Java persistence api 2.1

From Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEFrom Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEjaxconf
 
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
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5Smita B Kumar
 
Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Rohit Kelapure
 
BEA_eworld_2001_jta.ppt
BEA_eworld_2001_jta.pptBEA_eworld_2001_jta.ppt
BEA_eworld_2001_jta.pptssuser670564
 
J2EE - Practical Overview
J2EE - Practical OverviewJ2EE - Practical Overview
J2EE - Practical OverviewSvetlin Nakov
 
0012
00120012
0012none
 
Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501Tjarda Peelen
 
Configuring jpa in a Spring application
Configuring jpa in a  Spring applicationConfiguring jpa in a  Spring application
Configuring jpa in a Spring applicationJayasree Perilakkalam
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreIMC Institute
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)ejlp12
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architectureAnurag
 
Alive and Well with Java 8
Alive and Well with Java 8Alive and Well with Java 8
Alive and Well with Java 8Adam Pelsoczi
 

Similaire à Java persistence api 2.1 (20)

From Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEEFrom Tomcat to Java EE, making the transition with TomEE
From Tomcat to Java EE, making the transition with TomEE
 
Hibernate
HibernateHibernate
Hibernate
 
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
 
Advance java session 5
Advance java session 5Advance java session 5
Advance java session 5
 
Hibernate
HibernateHibernate
Hibernate
 
Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010
 
BEA_eworld_2001_jta.ppt
BEA_eworld_2001_jta.pptBEA_eworld_2001_jta.ppt
BEA_eworld_2001_jta.ppt
 
J2EE - Practical Overview
J2EE - Practical OverviewJ2EE - Practical Overview
J2EE - Practical Overview
 
J2 Ee Overview
J2 Ee OverviewJ2 Ee Overview
J2 Ee Overview
 
0012
00120012
0012
 
MyBatis
MyBatisMyBatis
MyBatis
 
Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501Alfresco Business Reporting - Tech Talk Live 20130501
Alfresco Business Reporting - Tech Talk Live 20130501
 
Introduction to Datastore
Introduction to DatastoreIntroduction to Datastore
Introduction to Datastore
 
Configuring jpa in a Spring application
Configuring jpa in a  Spring applicationConfiguring jpa in a  Spring application
Configuring jpa in a Spring application
 
Java Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : DatastoreJava Web Programming on Google Cloud Platform [2/3] : Datastore
Java Web Programming on Google Cloud Platform [2/3] : Datastore
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
C:\fakepath\jsp01
C:\fakepath\jsp01C:\fakepath\jsp01
C:\fakepath\jsp01
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
Alive and Well with Java 8
Alive and Well with Java 8Alive and Well with Java 8
Alive and Well with Java 8
 

Dernier

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 RobisonAnna Loughnan Colquhoun
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Dernier (20)

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
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
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...
 
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
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
How to 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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Java persistence api 2.1

  • 2. Agenda - Overview - OR Mapping and Entity Introduction - Entity Manager - Transactions - Persistence Context - Relationships - Query Capabilities - Criteria
  • 3. So, what's the big deal ? - Relational DB and Java are world apart - JDBC - Mandates manual marshaling - SQL Queries are difficult to manage - No compile time support - Boiler plate - Database portability - EJB 2.1 - Beast - Horrible to work with - Need of the hour : Lightweight POJO framework
  • 4. What we need to save the day ? - Higher level abstraction above JDBC - Provide object view of RDBMS resources - Simple to configure - Lightweight - Unobtrusive - Local, but Mobile - Integration and Testability - Above all, Fun to work with
  • 5. JPA - All of the items listed in prev slide and ... - Feature rich - Spec is about 500+ pages - More than one way to do, that way looks complex - Can be used in JavaEE as well as JavaSE environments - Wait, we do have alternatives - Data Mapper - Java Data Objects - JDBC
  • 6. History - JPA 1.0 (2006) - Part of EJB 3.0 Spec - Start over (Leaving Legacy Entity framework) - Leading ORM experts on the panel (Hibernate, TopLink, etc) - JPA 2.0 (2009) - Added significant amount of features to catch up with ORM vendors - Criteria API - Bean Validation - Metamodel - JPA 2.1 (2013) - Converters - Criteria Update/Delete - Stored Procedures
  • 7. Big Players - Client - JPA Spec API - JPA implementation - Hibernate - EclipseLink (prev TopLink) - Apache OpenJPA - Database Driver - DB - App Level : <persistence-unit> - DB location : JNDI or DB URL - List of Entity classes - JPA provider : Hibernate - Each Entity Class - Table name - Column names - Client that uses JPA API Code / Configuration
  • 8. Lab - 1 - Module Setup - Step 1 : Create a git repo - Step 2 : Create a maven module (all defaults) - Step 3 : Git commit - Step 4 : Add Dependencies - Client (JUnit) - JPA Spec API - Hibernate Core - Entity Manager - Database driver jar - Step 5 : Add JPA configuration file : persistence.xml - Step 6 : Assert em.isOpen() - Step 7 : Git commit
  • 9. OR Mapping - Class <-> Table - Property <-> Column - Properties without mapping to any column : Transient - Instance of Class <-> Row in the table - Relies on Convention over Configuration - Same old POJO underneath - Entities are still EJBs ? Yes and No ! - Typically created with new operator - Like SBs to container, Entities to EntityManager - Resides on server but client directly interacts with them unlike EJB siblings - Can define DB schema (not for production use)
  • 10. Lab - 2 : Find Employee - Step 1 : Employees Entity - Step 2 : persistence.xml using MySQL Employees DB - Step 3 : Assert employee presence - Step 5 : Getters and Setters - Step 6 : Updated test run
  • 11. Object-Relational Mapping - POJO needs something to become Entity - 2 Ways : Annotations or XML - Two types of Annotations - Logical - Describes object model - @Entity, @Basic, @Temporal etc. - Physical - Describes physical schema - @Table, @Column etc. - Configuration by Exception - Optional (Almost) - Can be specified on Fields or Bean Properties - Field annotations : Getters/Setters ignored - Bare minimum : @Entity and @Id annotations
  • 12. Mapping simple types - Java Primitive types and Wrappers - Byte[], Byte[], char[], Character[] - java.lang.String - java.math.BigInteger, BigDecimal - java.util.Date, Calendar - java.sql.Date, Time, Timestamp - Enums
  • 13. Entity, Who are you ? - Entity must have an identity - Annotate the field with @Id - Equivalent of primary key - Primary key not mandatory in DB table - Multiple rows with same value in @Id mapped column. Trouble! - Composite primary key - @IdClass - @EmbeddedId - @MapsId
  • 14. ID Generation - 4 Types - AUTO - For prototyping only - IDENTITY - SEQUENCE - TABLE - DB agnostic - IDENTITY and SEQUENCE need DB support
  • 15. Serializable Entities - Not mandated by Spec - Application can opt for when - Entities are shared across VMs - Entities are stored in (clustered/serialized) sessions
  • 18. Persistence Unit (Tangible) - Named configuration of entity classes
  • 19. EntityManager (Tangible) - Central authority - Qualifies simple POJOs into Entities - Almost entire API is built in this one interface - Provides API to - Do CRUD - Query - Synchronize with Database - Automatically sync to DB - 1st Level Caching - Works with JTA in server env
  • 20. EntityManager (Tangible) - Obtained from EntityManagerFactory - Not thread-safe and must not be shared between threads - Java EE - Can be obtained directly using CDI injection or JNDI lookup - Typically a transaction involves multiple components - Need same entity context all through the transaction - Multiple entity managers (within a tx) automatically points to same Persistence Context - We don't have to pass reference of EntityManager between calls - Java SE - Using standalone bootstrap class Persistence - Each call to emf.createEntityManager() creates a new isolated persistence context
  • 21. Persistence Context (Intangible) - Invisible - A set of managed Entity objects - Associated to a Persistence Unit - Managed by one or more EntityManagers - Only one Entity with same identity - Entities contained within are “managed”
  • 23. Transaction - ACID - Transaction Demarcation : Act of beginning or completing - JPA supports two types - Resource Local - JavaSE and JavaEE (without container support) applications - Always application demarcated - JTA - aka Global Transactions - Spans across resources (multiple DBs, Messaging server, etc…) - Demarcated by containers (most of the times)
  • 24. Transaction Contd... - Transaction Synchronization : Process by which a persistence context is registered with a transaction - Transaction Association : Act of binding a persistence context to a transaction - Transaction Propagation : Process of sharing a persistence context between multiple entity managers within a transaction
  • 25. Entity Manager Types - EntityManager can be - Container Managed Transaction-scoped - Container Managed Extended - Application scoped - Scope is defined when the EntityManager is created
  • 26. Container Managed Entity Manager - Mostly we are talking about Java EE environment - Injected via @PersistenceContext - No need to Open or Close it - Two flavors - Transaction Scoped - Extended
  • 27. Transaction Scoped - Default - Lives as long as Transaction is alive - Once transaction finished, all objects are detached - Lazily created : When an operation on EntityManager is called - @PersistenceContext hands over a proxy - Stateless - Maintenance free
  • 28. Transaction Scoped Contd... - Gets associated to the ongoing transaction seamlessly
  • 30. Extended Context - Meant for @Stateful beans only - Begins with EM creation and live till its closed - Eagerly created : As soon as the txn begins - The context gets destroyed when @Remove on SFSB is called - Extended spans transactions and manages Entities between Txns - Caching of Entity is not the objective but mostly you will be doing it
  • 31. Extended Context - Prevents Entities from becoming detached when txn ends - Client can use bean fields to hold state and interact with DB
  • 33. Application managed Context - Mostly Java SE environments - Can be used in Java EE Environment as well - Application is responsible for context’s life cycle - Extended by nature and spans multiple transactions - Needs Explicit - Creation : EntityManagerFactory.createEntityManager() - Flushing/Closing : EntityManager.close() - Is standalone and not propagated with transaction - Can join transaction by EntityManager.joinTransaction() - Typically used in Unit Testing
  • 34. Recommendations - Stateless Beans - Preferred way to manage persistence operations - Use @PersistantContext to inject EntityManager - Stateful Beans - Extended context - State can include EntityContext and its result data - Use JNDI lookup to get Stateful beans (no @Inject/@EJB) - In case of rollback, DO NOT revive the detached object
  • 35. Caching - Concept is to avoid going to DB by maintaining an in-sync object in memory - Entity Manager serves as 1st level cache - Infinispan is default for WildFly - Caching hurdles - In memory objects are not transactional - Data sync with Database - Memory occupancy
  • 36. Relationships in DB - Achieved via - Foreign Key - Mapping tables - Table with Foreign Key column is the owner
  • 37. A bit insights into DB
  • 38. Relationships - No Entity is an Island! - Table with foreign key always ends up with single association - Roles - Employee “works in” a Department - Department “has” employees working in it - One Entity can participate in many relationships - Directionality - Unidirectional - BiDirectional -
  • 39. Relationships Cntd... - Cardinality - One to One - One to Many - Many to One - Many to Many - Ordinality (aka Optionality)
  • 40. Relationships Myths - Way to avoid business logic - You still have to deal with CascadeType - Gives flexibility - Too little for too much price - Lazy Vs Eager loading - OpenEntityManagerInViewFilter - Shields developer from database - To very little extent - Often the cause for killer bugs/defects -
  • 41. Single Valued Associations - Cardinality of Target entity is 1 - ManyToOne - OneToOne - ManyToOne - Rules - @JoinColumn goes in Entity that has foreign key defined - @ManyToOne goes into the owning side i.e with foreign key - @OneToMany(mappedBy) goes into the target Entity in case of Bidirectional - OneToOne - Two Rules - @JoinColumn goes in Entity that has foreign key defined - @OneToOne(mappedBy) goes into the target Entity in case of Bidirectional -
  • 42. Many To One - Always Source has has attribute of Target type - Enables navigation from Source to Target - @ManyToOne and @JoinColumn - Table with foreign key is owning side - Ownership is important because of foreign key column - @JoinColumn is specified on the owning side - Many to One mappings are always on owning side
  • 43. Many To One - @JoinColumn is optional - Default join column : targetTable_targetIdColumn - @Column won’t gel with these annotations
  • 44. One To One - Almost similar to Many To One - @OneToOne and @JoinColumn - Table with foreign key is the owning side - @JoinColumn has to be on the side with foreign key
  • 45. One To One Bidirectional - Source Entity already has all the information - It just needs which property on source entity has it - @OneToOne(mappedBy)
  • 46. Collection Valued Associations - Source entity references one or more Target entities - OneToMany - ManyToMany
  • 47. One To Many - Nothing but Bidirectional ManyToOne - Always implies a ManyToOne presence - Always Bidirectional - Always on the target side i.e. Not the Source side - All configuration is in Source entity already - Just needs the Source entity property information - @OneToMany(mappedBy)
  • 48. Many To Many - @JoinColumn is not sufficient - Can be achieved only by a join table - Difficult to say who is the owner - Either can be the owner - The target side will have @ManyToMany(mappedBy) - Absence of mappedBy will make them unidirectional
  • 49. Many To Many Bidirectional - mappedBy on the target side - All it needs is the property configured in Source Entity
  • 50. One To Many using a @TableJoin - @OneToMany is not just bidirectional @ManyToOne - Can be achieved with a @TableJoin
  • 51. Lazy Relationships - Not specified, @ManyToOne and @OneToOne guaranteed to Eagerly load - Collection valued relationships by default is Lazily load - Provider may choose to do Eager loading
  • 52. Queries - CRUD - Retrieval Rules - As expected, constructed using EntityManager - API - Query - TypedQuery - Type - Static - Annotation or XML - Dynamic - JPQL - Criteria - Dynamic queries are expensive
  • 53. JPQL - Limited yet powerful - Metamodel is not mandatory (almost) - Limited compile time safety - Two types - @NamedQuery - Dynamic string query
  • 54. Criteria API - Programmatic control - Robust - Uses Objects instead of Strings - Can result in bloated code - More than One way to do it - Query is prepared dynamically - Allows flexible filtering
  • 55. Criteria Query - Entity Result
  • 56. References - JPA 2.1 Specification (Not for humans) - JPA 2.1 Java Doc (Amazingly small) - (Blog) JPA 2.1 – 12 features every developer should know - MySQL Employees Sample DB