100% found this document useful (1 vote)
287 views60 pages

Java Persistence API JPA Basics

The document provides an overview of the Java Persistence API (JPA) including what JPA is, why it is used, object-relational mapping, entity definitions and lifecycles, the entity manager and its operations, detached entities, and persistence contexts. Key topics covered include mapping objects to database tables, defining entities as POJOs, the entity manager for performing CRUD operations and managing entity state, and how the persistence context is accessed indirectly through the entity manager.

Uploaded by

GODZYLLA21
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
287 views60 pages

Java Persistence API JPA Basics

The document provides an overview of the Java Persistence API (JPA) including what JPA is, why it is used, object-relational mapping, entity definitions and lifecycles, the entity manager and its operations, detached entities, and persistence contexts. Key topics covered include mapping objects to database tables, defining entities as POJOs, the entity manager for performing CRUD operations and managing entity state, and how the persistence context is accessed indirectly through the entity manager.

Uploaded by

GODZYLLA21
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Java Persistence API (JPA): Basics

Sang Shin Java Technology Evangelist Sun Microsystems, Inc. javapassion.com


1

Agenda
Java Persistence Requirements O/R Mapping What is an entity? JPA Programming Model Entity Manager & life-cycle operations Detached Entities Entity life-cycle transition Persistence context and Entity Manager Transactions

Why Use ORM?


3

Why Object/Relational Mapping?


A major part of any enterprise application development project is the persistence layer

Accessing and manipulate persistent data typically with relational database

ORM handles Object-relational impedance mismatch

Data lives in the relational database, which is table driven (with rows and columns)

Relational database is designed for fast query operation of table-driven data

We want to work with objects, not rows and columns of table


4

What is & Why JPA?


5

What is JPA?

Java EE standard O/R Mapping framework Object/relational mapping framework for enabling transparent POJO persistence

Let you work without being constrained by tabledriven relational database model handles ObjectRelational impedance mismatch

Lets you build persistent objects following common OO programing concepts

Java Persistence Requirements

Java Persistence Requirements


Simplify the persistence model
> Default over configuration > Elimination of deployment descriptor

Provide light-weight persistence model


> Programming and deployment model > Runtime performance

Enable testability outside of the containers


> Test-driven development > Test entities as part of nightly-build process

Java Persistence Requirements


Support rich domain modelling
> Inheritance and polymorphism

Provide standardized and efficient Object/Relational (O/R) mapping


> Optimized for relational database > Standardize annotations and XML configuration files

Provide extensive querying capabilities Support for pluggable, third-party persistence providers

> Through persistence unit - represented by persistence.xml


9

Common Java Persistence Between J2SE and J2EE Environments


Persistence API expanded to include use outside of EJB container Evolved into common Java persistence API between Java SE and Java EE apps
> You can use new Java persistence API in Java SE, Web, and

EJB applications

10

O/R Mapping

O/R Mapping
Comprehensive set of annotations defined for mapping
> > > > >

Relationships Joins Database tables and columns Database sequence generators Much more

Specified using standard description elements in a separate mapping file or within the code as annotations

12

An Example Data Model


Customer
int id String name int c_rating Image photo Set<Order> orders Collection<Phone> phones ...

Order
M
int id Customer cust ...

Phone
N
int id Collection<Customer> custs ...

Maps entity state to data store Maps relationship to other entities

13

Simple Mapping
CUSTOMER
ID NAME CREDIT PHOTO

@Entity(access=FIELD) public class Customer { @Id int id; String name; @Column(name=CREDIT) int c_rating; @Lob Image photo; }

Mapping defaults to matching column name. Only configure if entity field and table column names are different.

14

What is an Entity?

What is an Entity?
Plain Old Java Object (POJO)
> Created by means of new keyword just like a normal Java

class > No need to implement interfaces unlike EJB 2.1 entity beans

May have both persistent and non-persistent state


> Non-persistent state (transient or @Transient)

Can extend other entity and non-entity classes Serializable; usable as detached objects in other tiers
> No need for data transfer objects

16

Entity Example
@Entity public class Customer implements Serializable { @Id protected Long id; protected String name; @Embedded protected Address address; protected PreferredStatus status; @Transient protected int orderCount; public Customer() {} public Long getId() {return id;} protected void setId(Long id) {this.id = id;} public String getName() {return name;} public void setName(String name) {this.name = name;} }

17

Entity Identity
Every entity has a persistence identity Can correspond to simple type
> Maps to primary key in database > @Idsingle field/property in entity class > @GeneratedValuevalue can be generated automatically

Can correspond to user-defined class

using various strategies (SEQUENCE, TABLE, IDENTITY, AUTO)

Must be defined on root of entity hierarchy or mapped superclass

> @EmbeddedIdsingle field/property in entity class > @IdClasscorresponds to multiple Id fields in entity class

18

Programming Model

Java Persistence Programming Model


Entity is a POJO (no need to implement EntityBean) Use of Annotation to denote a POJO as an entity (instead of deployment descriptor)
// @Entity is an annotation // It annotates Employee POJO class to be Entity @Entity public class Employee { // Persistent/transient fields // Property accessor methods // Persistence logic methods } 20

Another Persistence Entity Example


@Entity Annotated public class Customer { private Long id; private String name; private Address address; private Collection<Order> orders = new HashSet(); public Customer() {} @Id public Long getID() { return id; } protected void setID (Long id) { this.id = id; } ...

as Entity

@Id denotes primary key

Getters/setters to access state

21

Persistence Entity Example (Contd.)


...

// Relationship between Customer and Orders @OneToMany public Collection<Order> getOrders() { return orders; } public void setOrders(Collection<Order> orders) { this.orders = orders; } // Other business methods ...

22

Client View: From Stateless Session Bean


@Stateless public class OrderEntry { // Dependency injection of Entity Manager for // the given persistence unit @PersistenceContext EntityManager em; public void enterOrder(int custID, Order newOrder){ // Use find method to locate customer entity Customer c = em.find(Customer.class, custID); // Add a new order to the Orders c.getOrders().add(newOrder); newOrder.setCustomer(c);

} }

// other business methods

23

Client Code: From Java SE Client


public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeService"); EntityManager em = emf.createEntityManager(); Collection emps = em.createQuery("SELECT e FROM Employee e") .getResultList(); // More code

24

Entity Manager & Entity Life-cycle Operations

EntityManager
Similar in functionality to Hibernate Session, JDO PersistenceManager, etc. Controls life-cycle of entities
> > > >

persist() - insert an entity into the DB remove() - remove an entity from the DB merge() - synchronize the state of detached entities refresh() - reloads state from the database

26

Persist Operation
public Order createNewOrder(Customer customer) { // Create new object instance entity is in transient state Order order = new Order(customer); // After persist() method is called upon the entity, // the entity state is changed to managed. On the // next flush or commit, the newly persisted // instances will be inserted into the database table. entityManager.persist(order); return order;
27

Find and Remove Operations


public void removeOrder(Long orderId) { Order order = entityManager.find(Order.class, orderId); // The instances will be deleted from the table // on the next flush or commit. Accessing a // removed entity has undefined results. entityManager.remove(order); }
28

Merge Operation
public OrderLine updateOrderLine(OrderLine orderLine) { // The merge method returns a managed copy of // the given detached entity. Changes made to the // persistent state of the detached entity are // applied to this managed instance. return entityManager.merge(orderLine); }
29

Detached Entities

Detached Entities
Must implement Serializable interface if detached object has to be sent across the wire No need for DTO (Data Transfer Object) anti-design pattern Merge of detached objects can be cascaded

31

Transition to Detached Entities


When a transaction is committed or rollback'ed When an entity is serialized

32

Entity Life-cycle Transition

Entity Life-cycle

34

Demo #1
1. Creating Entities from Existing Database tables 2. Performing CRUD (Create, Read, Update, Delete) operations against Entities You can try this demo from www.javapassion.com/handsonlabs/ jpabasics

Persistence Context & Entity Manager

Persistence Context & Entity Manager


Persistence context
> Represents a set of managed entity instances at runtime > Entity instance is in managed state means it is contained in a

particular persistent context > Entity instances in a particular persistent context behaves in a consistent manner

Entity manager
> Performs life-cycle operations on entities manages

persistence context

37

Persistence Context & Entity Manager


Persistence context is not directly accessible to developers
> There is no programming API for accessing persistence

context there is no need > Persistence context is accessed indirectly through entity manager

The type of entity manager determines how a persistence context is created and removed Why do you care as a developer?
> Because inclusion or exclusion of an entity into/from the

persistence context will affect the outcome of any persistence operation on it


38

Types of Entity Managers

Types of Entity Managers


Container-Managed Entity Manager (Java EE environment)
> Transaction scope entity manager - our focus of discussion > Extended scope entity manager

Application-Managed Entity Manager (Java SE environment)

40

How Entity Manager Is Created


Different type of Entity Manager is created and acquired by an application differently
> Container-managed entity manager (for Java EE) is acquired by

an application through @PersistenceContext annotation the container creates an entity manager and injects it into the application > Application-managed entity manager (for Java SE) is created and closed by the application itself

41

Demo #2
Creating Entity Manager for Java SE Environment
You can try this demo from www.javapassion.com/handsonlabs/ jpabasics

Entity Managers & Persistence Context


Different type of Entity Manager creates and manages a persistence context differently
> The lifetime of persistence context is determined by the type of

Entity manager

43

Transaction-Scope Entity Manager


Persistence context is created when a transaction gets started and is removed when the transaction is finished (committed or rolled-back)
> The life-cycle of the persistence context is tied up with

transactional scope

Persistence context is propagated


> The same persistence context is used for operations that are

being performed in a same transaction

The most common entity manager in Java EE environment


44

Extended-Scope Entity Manager


Extended-scope Entity manager work with a single persistent context that is tied to the life-cycle of a stateful session bean

45

Persistence Unit

Persistence Unit
All entities managed by a single EntityManager is defined by a persistence unit A persistence unit defines
> all entities that are co-located > mapped onto a single database

persistence.xml defines one or more persistence unit


<persistence-unit name="OrderManagement"> <mapping-file>mappings.xml</mapping-file> <jar-file>order.jar</jar-file> <transaction-type>JTA</transaction-type> </persistence-unit>
47

Persistence Unit
Persistence Context same entity
Entity Manager Entity Manager

Persistence Context

Data source
48

Transactions

Transaction Types
Two different transaction types
> Resource-local transactions > JTA (Java Transaction API) > Multiple participating resources > Distributed XA transactions

Transaction type is defined in persistence unit (persistence.xml file)


> Default to JTA in a Java EE environment > Default to RESOURCE_LOCAL in a Java SE environment

50

@TransactionAttribute Annotation
TransactionAttributeType.REQUIRED TransactionAttributeType.REQUIRES_NEW TransactionAttributeType.MANDATORY TransactionAttributeType.NOT_SUPPORTED TransactionAttributeType.NEVER TransactionAttributeType.SUPPORTS

51

Entity Manager and Transaction Type


Container managed entity manager use JTA transactions Propagation of persistence context with a JTA transaction is supported by the container
> Sharing same persistence context among multiple entity

managers

52

Transactions & Persistence Context


Transactions define when new, modified, or removed entities are synchronized with the database How persistence context is created and used is determined by
> Transaction type (JTA or Resource-local) and > Transaction attribute (REQUIRED or ..)

53

Demo #3
Use two different transaction attributes and see how persistence context is propagated. You can try this demo from www.javapassion.com/handsonlabs /jpabasics

Demo Scenarios
There are two stateless beans
> EmployeeServiceBean (Calling bean) > AuditServiceBean (Callee bean)

#1: The createEmployee() method of the EmployeeServiceBean invokes logTransaction() method of the AuditServiceBean
> logTransaction() is set with

TransactionAttributeType.REQUIRED annotation

#2: The createEmployee2() method of the EmployeeServiceBean invokes logTransaction2() method of the AuditServiceBean
> logTransaction2() is set with

TransactionAttributeType.REQUIRES_NEW annotation

55

EmployeeServiceBean (Calling Bean)


@Stateless public class EmployeeServiceBean implements EmployeeService { @PersistenceContext(unitName="EmployeeService") private EntityManager em; @EJB AuditService audit; public void createEmployee(Employee emp) { em.persist(emp); audit.logTransaction(emp.getId(), "created employee"); } public void createEmployee2(Employee emp) { em.persist(emp); audit.logTransaction2(emp.getId(), "created employee"); }

56

AuditServiceBean (Callee Bean)


@Stateless public class AuditServiceBean implements AuditService { @PersistenceContext(unitName="EmployeeService") private EntityManager em; @TransactionAttribute(TransactionAttributeType.REQUIRED) //Default public void logTransaction(int empId, String action) { // verify employee number is valid if (em.find(Employee.class, empId) == null) { throw new IllegalArgumentException("Unknown employee id"); } LogRecord lr = new LogRecord(empId, action); em.persist(lr); } @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) public void logTransaction2(int empId, String action) { // ... same code as logTransaction() ... }

57

Behind the Scene: Scenario #1


The createEmployee() method of the EmployeeServiceBean (Calling bean) invokes logTransaction() method of the AuditServiceBean (Callee bean)
> logTransaction() of AuditServiceBean (Bean #2) is set with

TransactionAttributeType.REQUIRED annotation

The createEmployee() method of Bean #1 starts a new transaction A as default, thus creating a persistence context A
> The newly created Employee object A belongs to persistence context A

The transaction A and persistence context A of createEmploy() method of Calling bean is propagated to the logTransaction() method of Callee bean
> The logTransaction() method has access to Employee object A

58

Behind the Scene: Scenario #2


The createEmployee2() method of the EmployeeServiceBean (Calling bean) invokes logTransaction2() method of the AuditServiceBean (Callee bean) > logTransaction2() of AuditServiceBean (Callee bean) is set with TransactionAttributeType.REQUIRES_NEW annotation The createEmployee2() method of Calling bean starts a new transaction A as default, thus creating a persistence context A > The newly created Employee object A belongs to persistence context A The logTransaction2() method of Callee bean creates a new transaction B, thus a new persistence context B > The persistence context B does not have Employee object A > Employee object A still belongs to persistence context A > em.find() will fail 59

Thank You!

60

Common questions

Powered by AI

JPA addresses object-relational impedance mismatch by providing a robust object-relational mapping framework that bridges the gap between object-oriented systems and relational databases. It allows developers to work with objects using standard Java language constructs, while JPA itself handles the translation to relational databases . JPA facilitates this mapping using a comprehensive set of annotations, which define relationships, database tables and columns, sequence generators, and more . Additionally, these mappings can be specified using standard description elements in separate mapping files or coded annotations, providing flexibility in how developers choose to implement them based on the specific requirements of their project .

In a transaction-scope entity manager, the persistence context is created at the start of a transaction and is disposed of upon transaction completion. This means that each transaction has its own isolated persistence context, making it suitable for handling transient, independent operations . Conversely, an extended-scope entity manager ties the persistence context to the lifecycle of a stateful session bean rather than individual transactions, allowing entities to be shared across multiple transactions. This allows entity instances to be continuously managed and accessed until the stateful bean is destroyed, making it efficient for operations requiring long-lived entity management and consistency across multiple transactions .

The persistence unit in JPA plays a crucial role in defining the database configuration for a group of entities managed by a single EntityManager. It is configured in the persistence.xml file and specifies configurations such as the list of entity classes, the data source, and the transaction type, whether JTA or RESOURCE_LOCAL . By providing a cohesive configuration for entities, the persistence unit enables efficient database interactions, as all entities are co-located and mapped onto a single database, facilitating unified transaction management and data consistency . This common configuration also simplifies deployment and integration of JPA components across various development and production environments .

The @Id annotation in JPA is used to define a simple persistence identity, marking a field as the primary key of the entity, which serves as the unique identifier within the database . The @GeneratedValue annotation facilitates automatic generation of the primary key values using different strategies such as SEQUENCE, TABLE, IDENTITY, and AUTO, which abstract the key generation logic from the developer, ensuring that each entity persists with a unique identifier . These annotations are crucial for defining and managing the unique identity of entities, allowing JPA to efficiently manage and track entities across transactions and database operations .

Using annotations in JPA significantly enhances the developer experience compared to previous versions like EJB 2.1 by reducing boilerplate code and improving readability and maintainability of the code. Annotations allow developers to mark classes as entities directly using @Entity without the need for cumbersome XML configuration files or lengthy deployment descriptors . This simplifies the development process by embedding the configuration within the code itself, making it intuitive and self-explanatory. Moreover, annotations facilitate a more clear mapping of classes and their properties to database tables and columns, which aligns well with Object-Oriented Programming practices .

Detached entities in JPA differ from managed entities primarily in their relationship with the persistence context. While managed entities are actively tracked by the persistence context and their changes automatically synchronized with the database, detached entities are no longer associated with any persistence context once the transaction is completed or rolled back . Despite this disassociation, detached entities can be serialized and transferred across various application layers, avoiding the need for Data Transfer Objects (DTOs). An advantage they offer is the ability to operate over entity data across different layers without being constrained by the transaction boundaries, thus facilitating greater application scalability and flexibility .

JPA supports both container-managed and application-managed entity managers to cater to different application environments. Container-managed entity managers are typically used in Java EE environments where the container manages the entity manager's lifecycle, providing benefits such as automatic JTA transaction management and ease of integration with other Java EE components . These are appropriate for applications requiring complex transactions and integration with other enterprise resources. On the other hand, application-managed entity managers are used in Java SE environments, allowing developers more control over the entity manager's lifecycle and transactions. This setup is suitable for simpler applications or scenarios where developers need to manage transactions directly due to specific application logic requirements .

The entity manager is crucial in managing persistence contexts within JPA, as it handles the life-cycle operations of entities. It serves as an interface between the Java application and the database, ensuring that entities are persisted, retrieved, and removed according to the application’s needs . The entity manager manages the persistence context, which is a set of managed entity instances. The type and scope of the entity manager, whether container-managed or application-managed, determine the creation and removal of the persistence context . These contexts affect the lifecycle of entities by deciding when they enter into managed states or change to detached states, impacting how and when their states are synchronized with the database .

The Java Persistence API (JPA) offers several key advantages in enterprise application development: it simplifies the persistence model by providing default configurations over extensive configurations, thus eliminating the need for deployment descriptors . JPA provides a lightweight persistence model that enhances runtime performance and facilitates test-driven development through testability outside of the containers . It supports rich domain modeling with features like inheritance and polymorphism, and provides standardized, efficient Object/Relational mapping optimized for relational databases . Furthermore, JPA extends extensive querying capabilities and supports the integration of third-party persistence providers, which can be especially beneficial in large-scale enterprise applications .

Using a transaction-scope entity manager is beneficial in scenarios where each transaction requires a fresh persistence context, often in stateless applications or when operations are performed independently, without needing to retain context between transactions . This type of entity manager creates a new persistence context when a transaction begins and disposes of it when the transaction is completed, making it ideal for isolated operations that don't share entities across transactions. In contrast, an extended-scope entity manager maintains the same persistence context across multiple transactions, which is advantageous for stateful session beans where entity instances are kept beyond transactional boundaries for operations needing continuity across business processes .

You might also like