JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.

Slides:



Advertisements
Similar presentations
V 6, Mats Strandberg ORM With Hibernate.
Advertisements

Introduction to NHibernate By Andrew Smith. The Basics Object Relation Mapper Maps POCOs to database tables Based on Java Hibernate. V stable Generates.
Persistence Jim Briggs 1. 2 Database connectivity: JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets)
JBoss Seam: Contextual Components Jason Bechtel
Entities and Persistence. Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational.
Advanced Java programming (Java EE)
1 Lecture 18 George Koutsogiannakis/Spring 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
An Introduction to Hibernate Matt Secoske
The Java Persistence API Edel Sherratt. Contents Revisit applications programming Using Java Persistence API.
Data Persistence and Object-Relational Mapping Slides by James Brucker, used with his permission 1.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
Java Persistence API Maciej Adamiak. Agenda -Entity, -Entity Operations, -Query Language.
Rice KRAD Data Layer JPA Design Eric Westfall July 2013.
CSE446 S OFTWARE Q UALITY M ANAGEMENT Spring 2014 Yazılım ve Uyguluma Geliştirme Yöneticisi Orhan Başar Evren.
2007 JavaOne SM Conference | Session BOF-4181 | BOF-4181 Migrating a Spring/Hibernate Application to Java Platform, Enterprise Edition (Java EE) 5 Adrian.
Agenda What is Hibernate Spring Integration Questions Overview
Maven for building Java applications By Nalin De Zoysa
1 Lecture 17 George Koutsogiannakis/SUMMER 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
Java Persistence API Mario Peshev National Academy for Software Development academy.devbg.org Svetlin Nakov National Academy for Software Development academy.devbg.org.
Entity Beans BMP Celsina Bignoli
1 Java Persistence API JPA. 2 Agenda Motivation JPA Entities EntityManager & the Persistent Context Persistence Units Exceptions JPA Query Language.
IS-907 Java EE JPA: Simple Object-Relational Mapping.
Container-Managed Persistence (CMP) Entity Beans Lesson 3A / Slide 1 of 42J2EE Server Components Objectives In this lesson, you will learn to: Identify.
EJB 3.0 Persistence Sang Shin Java Technology Architect
EJB Framework.  As we know, EJB is the center of the J2EE architecture that provides a sturdy framework for building enterprise applications. The major.
Introduction to Entities
CS 157B: Database Management Systems II February 4 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.
Enterprise Java Java Persistence: EntityManager. Enterprise Java v070903Java Persistence: EntityManager2 Goals Become familiar with the Java Persistence.
1 Mapping Persistent Objects Entities represent data in the database, so changes to an entity bean result in changes to the database. That's ultimately.
EJB 3.0 Persistence Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.
Hibernate 3.0. What is Hibernate Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it.
1 Persistence in Java Enterprise Container Managed Persistence Application Managed Persistence Michael Brockway Sajjad Shami CG0165: Advanced Applications.
Creating competitive advantage Copyright © 2003 Enterprise Java Beans Presenter: Wickramanayake HMKSK Version:0.1 Last Updated:
Middleware Technology (J2EE/EJB) Entity Bean (JBoss EJB 3.0 tutorial)
Java Persistence API v1.0 a standard for ORM frameworks and POJO based Persistence Magnus Larsson
Topic : Hibernate 3:Advanced ORM Kaster Nurmukan.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
1 Persistence: EntityManager In Java EE 5, persistence has been spun off into its own specification: Java Persistence 1.0. Persistence provides an ease-of-use.
Faculty of Information Technology Advanced Java programming (J2EE) Java Persistence API Based on the JPA presentation from javabeat.net.
The Java Persistence API ©SoftMoore ConsultingSlide 1.
Java Persistence API part 1 INFORMATICS ENGINEERING – UNIVERSITY OF BRAWIJAYA Eriq Muhammad Adams J
v110912Java Persistence: EntityManager2 Overview Earlier versions of EJB Specification defined the persistence layer –javax.ejb.EntityBean Java EE 5 moved.
By Srinivas Mahakud Java Persistence API JPA. Review Topics: Introduction what is the JPA? What is the JPA contains of? Why developers should Create the.
Java Persistence API (JPA) Relationships. Kinds of relationships UML associations and aggregations (ER non- identifying relationships, shared semantics)
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February
JPA The New Enterprise Persistence Standard Mike Keith
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
IS-907 Java EE Introduction to JPA. Java Persistence API A framework for using relational databases in Java programs mapping between tables and classes,
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
1 Entity Callbacks and Listeners When you execute EntityManager methods like persist( ), merge( ), remove( ), and find( ), or when you execute EJB QL queries,
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA (I) Chengyu Sun California State University, Los Angeles.
Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan Java Annotation Lesson 1.
Object-Relational Mapping. Contents  Default Mapping Rules  Elementary Mapping  Embeddables  Relationship Mapping  Inheritance Mapping.
CS520 Web Programming Object-Relational Mapping with Hibernate and JPA Chengyu Sun California State University, Los Angeles.
Don't Know Jack About Object-Relational Mapping?
CS6320 – Java Persistence API
Chengyu Sun California State University, Los Angeles
Java Persistence Architecture (JPA)
Chengyu Sun California State University, Los Angeles
Advanced Java Programming
Hibernate (JPA) Code First Entity Relations
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
Chengyu Sun California State University, Los Angeles
Developing and testing enterprise Java applications
Topics Persistence API for JAVA EE5 Java Transaction API Entity class.
Chengyu Sun California State University, Los Angeles
Presentation transcript:

JPA Java Persistence API

Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications Created as part of EJB 3.0 within JSR 220 Merger of expertise from TopLink, Hibernate, JDO, EJB vendors and individuals Released May 2006 as part of Java EE 5 Integration with Java EE web and EJB containers provides enterprise “ease of use” features Can also be used in Java SE

Java Persistence Java Persistence consists of three areas: The Java Persistence API The query language Object/relational mapping metadata JPA reference implementation TopLink Essentials by GlassFish project javax.persistence package open source (under CDDL license)

Entities An entity is a lightweight persistence domain object Java class that typically represents a table in a relational database, instances correspond to rows Requirements: annotated with the javax.persistence.Entity annotation public or protected, no-argument constructor the class must not be declared final no methods or persistent instance variables must be declared final

Requirements for Entities (cont.) May be Serializable, but not required Only needed if passed by value (in a remote call) Entities may extend both entity and non-entity classes Non-entity classes may extend entity classes Persistent instance variables must be declared private, protected, or package-private No required business/callback interfaces class Employee{... }

Persistent Fields and Properties The persistent state of an entity can be accessed: through the entity’s instance variables through JavaBeans-style properties Supported types: primitive types, String, other serializable types, enumerated types other entities and/or collections of entities embeddable classes All fields not annotated or not marked as Java transient will be persisted to the data store!

Primary Keys in Entities Each entity must have a unique object identifier (persistent public class Employee private int id; private String name; private Date age; public int getId() { return id; } public void setId(int id) { this.id = id; }... } primary key

Persistent Identity Identifier (id) in entity = primary key in database Uniquely identifies entity in memory and in DB Persistent identity types: Simple id – single int id; Compound id – multiple int String name; Embedded id – single field of PK class EmployeePK id;

private int id; Identifiers can be generated in the database by on the identifier Four pre-defined generation strategies: AUTO, IDENTITY, SEQUENCE, TABLE Generators may pre-exist or be generated Specifying strategy of AUTO indicates that the provider will choose a strategy

Customizing the Entity Object In most of the cases, the defaults are sufficient By default the table name corresponds to the unqualified name of the class Customization: The defaults of columns can be customized using = “FULLTIME_EMPLOYEE") public class Employee{ …… } = “EMPLOYEE_ID”, nullable = false) private String = “FULL_NAME” nullable = true, length = 100) private String name;

Entity Relationships There are four types of The direction of a relationship can be: bidirectional – owning side and inverse side unidirectional – owning side only Owning side specifies the physical mapping

Relation Attributes CascadeType ALL, PERSIST, MERGE, REMOVE, REFRESH FetchType LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)

ManyToOne Mapping public class Sale { int id;... Customer cust; } SALE CUST_ID @Id...

OneToMany Mapping public class Sale { int id;... Customer cust; } public class Customer { int id;... Set sales; } CUSTOMER ID... “ cust ” )

ManyToMany public class Customer name="CUSTOMER_SALE", name="CUSTOMER_ID",referencedColumnName="customer_id"), name="SALE_ID", referencesColumnName="sale_id") Collection sales; public class Sale Collection customers; }

Entity Inheritance An important capability of the JPA is its support for inheritance and polymorphism Entities can inherit from other entities and from non-entities annotation identifies a mapping strategy: SINGLE_TABLE JOINED TABLE_PER_CLASS

@DiscriminatorColumn(name="DISC", public class Customer public class ValuedCustomer extends Customer {... } SINGLE_TABLE strategy - all classes in the hierarchy are mapped to a single table in the database Discriminator column - contains a value that identifies the subclass Discriminator type - {STRING, CHAR, INTEGER} Discriminator value - value entered into the discriminator column for each entity in a class hierarchy

Managing Entities Entities are managed by the entity manager The entity manager is represented by javax.persistence.EntityManager instances Each EntityManager instance is associated with a persistence context A persistence context defines the scope under which particular entity instances are created, persisted, and removed

Persistence Context A persistence context is a set of managed entity instances that exist in a particular data store Entities keyed by their persistent identity Only one entity with a given persistent identity may exist in the persistence context Entities are added to the persistence context, but are not individually removable (“detached”) Controlled and managed by EntityManager Contents of persistence context change as a result of operations on EntityManager API

Application Persistence Context Entities MyEntity A MyEntity B MyEntity C MyEntity a EntityManager MyEntity b Entity state Persistence Context

Entity Manager An EntityManager instance is used to manage the state and life cycle of entities within a persistence context The EntityManager API: creates and removes persistent entity instances finds entities by the entity’s primary key allows queries to be run on entities There are two types of EntityManagers: Application-Managed EntityManagers Container-Managed EntityManagers

Application-Managed EntityManager Applications create EntityManager instances by using directly Persistence and EntityManagerFactory: javax.persistence.Persistence Root class for obtaining an EntityManager Locates provider service for a named persistence unit Invokes on the provider to obtain an EntityManagerFactory javax.persistence.EntityManagerFactory Creates EntityManagers for a named persistence unit or configuration

Application-Managed EntityManager public class PersistenceProgram { public static void main(String[] args) { EntityManagerFactory emf = Persistence.createEntityManagerFactory(“SomePUnit”); EntityManager em = emf.createEntityManager(); em.getTransaction().begin(); // Perform finds, execute queries, // update entities, etc. em.getTransaction().commit(); em.close(); emf.close(); }

Container-Managed EntityManagers An EntityManager with a transactional persistence context can be injected by using annotation public class BookmarkSeviceImpl implements BookmarkService private EntityManager em; public void save(Bookmark bookmark) { if (bookmark.getId() == null) { em.persist(bookmark); } else { em.merge(bookmark); }

Transactions JPA transactions can be managed by: the users application a framework (such as Spring) a J2EE container Transactions can be controller in two ways: Java Transaction API (JTA) container-managed entity manager EntityTransaction API ( tx.begin(), tx.commit(), etc) application-managed entity manager

Operations on Entity Objects EntityManager API operations: persist() - Insert the state of an entity into the db remove() - Delete the entity state from the db refresh() - Reload the entity state from the db merge() - Synchronize the state of detached entity with the pc find() - Execute a simple PK query createQuery() - Create query instance using dynamic JP QL createNamedQuery() - Create instance for a predefined query createNativeQuery() - Create instance for an SQL query contains() - Determine if entity is managed by pc flush() - Force synchronization of pc to database

Entity Instance’s Life Cycle Instances are in one of four states: New Managed Detached Removed The state of persistent entities is synchronized to the database when the transaction commits To force synchronization of the managed entity to the data store, invoke the flush() method

Persistence Units A persistence unit defines a set of all entity classes that are managed by EntityManager instances in an application For example, some set of entities can share one common provider (Toplink), whereas other set of entities can depend on a different provider (Hibernate) Persistence units are defined by the persistence.xml configuration file

persistence.xml A persistence.xml file defines one or more persistence units oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider jdbc/sample com.javabeat.ejb30.persistence.entities.mobile.MobileEntity org.hibernate.ejb.HibernatePersistence jdbc/sample com.javabeat.ejb30.persistence.entities.mobile.OtherEntity

Example of Spring Configuration EntityManager injection <bean id="entityManagerFactory“ class= "org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"> <bean class= "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">

Example of Spring Configuration Data source bean <bean id="dataSource“ class= "org.springframework.jdbc.datasource.DriverManagerDataSource">

Example of Spring Configuration Transaction Manager injection <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">

Resursi The Java Persistence API - A Simpler Programming Model for Entity Persistence Article “Introduction to Java Persistence API” roduction_to_java_persistence_api_jpa_ejb_3_0_1.php roduction_to_java_persistence_api_jpa_ejb_3_0_1.php Using the Java Persistence API with Spring medrec.html medrec.html TopLink Essentials (reference implementation)

Resursi JPA Annotation Reference resources/toplink-jpa-annotations.html resources/toplink-jpa-annotations.html