Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.

Slides:



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

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
Introduction to Enterprise JavaBeans. Integrating Software Development Server-side Component Model Distributed Object Architecture –CORBA –DCOM –Java.
Entities and Persistence. Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational.
Session-02.
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.
Introduction to JPA Java Persistence API Introduction to JPA.
Hibernatification! Roadmap for Migrating from Plain Old SQL on JDBC to JPA on Hibernate Duke Banerjee Senior Developer, DrillingInfo.com.
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.
Towards Bboogle 3.0.0: a Technical Walkthrough Patricia Goldweic Sr. Software Engineer AR&T, Northwestern University Brian Nielsen Manager, Faculty Support.
2007 JavaOne SM Conference | Session BOF-4181 | BOF-4181 Migrating a Spring/Hibernate Application to Java Platform, Enterprise Edition (Java EE) 5 Adrian.
Spring Overview, Application demo -Midhila Paineni 09/23/2011 Spring Overview, Application demo9/8/20151.
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.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
Entity Beans BMP Celsina Bignoli
IS-907 Java EE JPA: Simple Object-Relational Mapping.
Enterprise JavaBeans. What is EJB? l An EJB is a specialized, non-visual JavaBean that runs on a server. l EJB technology supports application development.
JBoss Seam Presented by Andy Nguyen Truc Pham. What is JBoss Seam? Created by Gavin King Created by Gavin King A lightweight framework for Java EE 5.0.
CS 157B: Database Management Systems II February 4 Class Meeting Department of Computer Science San Jose State University Spring 2013 Instructor: Ron Mak.
Enterprise Java Java Persistence: EntityManager. Enterprise Java v070903Java Persistence: EntityManager2 Goals Become familiar with the Java Persistence.
Enterprise Java v120215Java Persistence: EntityManager1.
EJB 3.0 Persistence Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.
Hibernate Persistence. What is Persistence Persist data to database or other storage.  In OO world, persistence means persist object to external storage.
1 Architectural Overview For application developers, assembling enterprise beans requires little or no expertise in the complex system-level issues that.
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.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005.
A U.S. Department of Energy Office of Science Laboratory Operated by The University of Chicago Argonne National Laboratory Office of Science U.S. Department.
JPA / HIBERNATE CSCI 6370 Nilayan Bhattacharya Sanket Sable.
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.
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.
The Java Persistence API ©SoftMoore ConsultingSlide 1.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
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.
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February
Java Programming: Advanced Topics 1 Enterprise JavaBeans Chapter 14.
JPA The New Enterprise Persistence Standard Mike Keith
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool Used in data layer of applications Implements JPA.
Introduction – ORM, Helloworld Application
IS-907 Java EE Introduction to JPA. Java Persistence API A framework for using relational databases in Java programs mapping between tables and classes,
Enterprise Java v121030Java EE Transactions1. Enterprise Java v121030Java EE Transactions2 Goals Understand the basic concepts behind a transaction Be.
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,
CS422 Principles of Database Systems Object-Relational Mapping (ORM) Chengyu Sun California State University, Los Angeles.
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 Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
Don't Know Jack About Object-Relational Mapping?
CS6320 – Java Persistence API
Chengyu Sun California State University, Los Angeles
Java Persistence Architecture (JPA)
Advanced Java Programming
Hibernate Bayu Priyambadha, S.Kom.
Developing and testing enterprise Java applications
CS4961 Software Design Laboratory Understand Aquila Backend
Topics Persistence API for JAVA EE5 Java Transaction API Entity class.
Chengyu Sun California State University, Los Angeles
Presentation transcript:

Topic : JPA Kaster Nurmukan

Overview of JPA EntityManager

O/R Mapping Primary entity annotations EntityManager Entity Relationships Practice

Database Table POJO Forward Engineering Reverse Engineering Java Persistence API

Java Persistence API (JPA) –Annotations for object-relational mapping –Data access API –An object-oriented query language JPQL Hibernate –The most popular Java ORM library –An implementation of JPA

Hibernate without JPA –API: SessionFactory, Session, Query, Transaction –More features Hibernate with JPA –API: EntityManagerFactory, EntityManager, Query, Transaction –Better portability –Behaviors are better defined and documented

Java classes – Employee.java JPA configuration file – persistence.xml Code to access the persistent objects – EmployeeTest.java (Optional) Logging configuration files – log4j.properties

Plain Java classes (POJOs); however, it is recommended that –Each persistent class has an identity field –Each persistent class implements the Serializable interface –Each persistent field has a pair of getter and setter, which don’t have to be public

@Entity. Mark class as an Define primary Define composite Define table name for entity Define column Ignored by persistence framework. Autopopulate column with sequence generator.

Maintains a cache of instances within a transactional context (persistence context) We can acquire EntityManager instance using :  Dependency Injection  EntityManagerFactory  JNDI Lookup Operations : persist(), merge(), remove(), find(), createNamedQuery(), createQuery() Persistence unit is declared in persistence.xml

@OneToOne. One to One is represented by a single- value entity reference at one or both ends of the This annotation is added to a Collection relationship Indicating that is an entity is part of a This annotation is assigned to a Collection relationship field to indicate the target entity also has a Collection of the source entity type. Lazy vs Eager Binding Cascade (ALL, PERSIST, MERGE, REMOVE, REFRESH)

v110912Java Persistence: EntityManager12 javax.persistence.EntityManager Replaces much of the EJB 2.x “Home” functionality Handles O/R Mapping of Entities to the database Provides APIs – inserting objects into database – getting objects from database – synchronizing objects with database – querying database Provides caching Coordinates with transactional services (JTA) Tightly integrated with Java EE and EJB, but not limited to that environment

v110912Java Persistence: EntityManager13 javax.persistence.EntityManager Replaces much of the EJB 2.x “Home” functionality Handles O/R Mapping of Entities to the database Provides APIs – inserting objects into database – getting objects from database – synchronizing objects with database – querying database Provides caching Coordinates with transactional services (JTA) – Tightly integrated with Java EE and EJB, but not limited to that environment

v110912Java Persistence: EntityManager14 Entities (formerly and sometimes still called Entity Beans) are now Plain Old Java Objects (POJOs) – nothing special happens when calling new Author author = new Author(); are not persistent until associated with an EntityManager em.persist(author);

v110912Java Persistence: EntityManager15 Example Author POJO public class Author { private long id; private long version=0; private String firstName; private String lastName; private String subject; private Date publishDate; public Author() {} public Author(long id) { this.id = public long getId() { return id;} private void setId(long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; }... } Warning: Using GeneratedValue without specifying a specific strategy should only be used when you have no intention of controlling how the provider manages primary keys for this object type. This would be rare.

v110912Java Persistence: EntityManager16 Creating Entity in Database Author author = new Author(); //primary key will be gen author.setFirstName("dr"); author.setLastName("seuss"); author.setSubject("children"); author.setPublishDate(new Date()); log_.info("creating author:" + author); em.persist(author); log_.info("created author:" + author); //output -creating author:id=0, fn=dr, ln=seuss, subject=children, pdate=Fri Sep 15 11:54:15 EDT created author:id=50, fn=dr, ln=seuss, subject=children, pdate=Fri Sep 15 11:54:15 EDT 2006

v110912Java Persistence: EntityManager17 Managed and Unmanaged Entities Unmanaged state (detached) – instance not associated with an EntityManager – state changes are not tracked – can be serialized to client and returned to be synchronized with database – nothing equivalent to this state in EJB 2.1 entity beans Managed state (attached) – instance associated with an EntityManager – state changes are tracked within a Persistence Context – EJB 2.1 entity beans were always managed client interfaced with data through a proxy or state transferred through a Data Transfer Object

v110912Java Persistence: EntityManager18 Persistence Context A set of attached entity instances managed by an EntityManager All entities become detached once closed Two types – Transaction-scoped Persistence Contexts begin/end at transaction boundaries only made available through container managed persistence contexts – Extended Persistence Contexts live beyond any single transaction allow longer-lived interactions with database without lengthy transactions tying up database resources

19 Persistence Context Examples Transaction-scoped (inside server EntityManager public void update(long authorId, String type) { Author author = em.find(Author.class, authorId); author.setType(type); } Extended (inside or outside server container) EntityManager em = Persistence. createEntityManagerFactory(“jpaDemo”).createEntityManager (); tx.begin(); //tx 1 begins Author author = em.find(Author.class, authorId); tx.commit(); //tx 1 ends, but author remains managed... tx.begin(); //tx 2 begins author.setType(type); tx.commit(); //tx 2 ends, and author is still managed until close

20 Persistence Unit A set of classes that are mapped to the database defined in META-INF/persistence.xml must have an identity – “” is a valid identity Classes – may be named in persistence.xml file – may be automatically scanned for in the classpath orm.xml – optionally provided to augment, provide, or replace class persistence metadata – (more on orm.xml in Core ORM topic)

v110912Java Persistence: EntityManager21 Example Component Layout META-INF/ +---persistence.xml ejava + ---examples +---… +---DAOException.class +---AuthorDAO.class +---jpa | +---JPAAuthorDAO.class | +---JPADAOBase.class +--domain +---Author.class

22 Example persistence.xml <persistence xmlns=" xmlns:xsi=" xsi:schemaLocation=" version="1.0"> java:/ejavaDS <property name="hibernate.show_sql" value="true"/ referenced by name global JNDI name by which provider references resource (will be used when deployed within server) may use properties element in Java SE environments that lack JNDI vendor-specific way to configure persistence provider

v110912Java Persistence: EntityManager23 Another Example persistence.xml <persistence xmlns=" xmlns:xsi=" xsi:schemaLocation=" version="1.0"> org.hibernate.ejb.HibernatePersistence <property name="hibernate.cache.provider_class" value="net.sf.ehcache.hibernate.Provider"/> <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/> <property name="hibernate.connection.url" value="jdbc:hsqldb:hsql://localhost:9001"/> <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/> <property name="hibernate.connection.password" value=""/> <property name="hibernate.connection.username" value="sa"/> </persistence

24 persistence.xml elements name – identity to reference Persistence Unit provider – fully qualified name of javax.persistence.PersistenceProvider – not needed if provider found in classpath acceptable mapping-file – resource path to optional mapping file – can be used to specify es or details jta-data-source – vendor-specific reference to data source using JTA transactions non-jta-data-source – vendor-specific reference to data source using RESOURCE_LOCAL transactions jar-file – optional/additional jar file to scan for classes class – specifies entity classes not automatically scanned by provider exclude-unlisted-classes – if set, provider will not automatically scan archive for entity classes properties – may be used to provide vendor-specific properties to configure persistence providers

25 Java SE Steps Startup – Get EntityManagerFactory Runtime – Create EntityManager – Start Transaction – Interact with Entity Manager – Commit Transaction – Close EntityManager Shutdown – Close EntityManagerFactory

26 updating entities Updates to managed entities automatically get propagated to database according to flush policy public Author update(Author author) { Author dbAuthor = em.find(Author.class,author.getId()); dbAuthor.setFirstName(author.getFirstName()); dbAuthor.setLastName(author.getLastName()); dbAuthor.setSubject(author.getSubject()); dbAuthor.setPublishDate(author.getPublishDate()); return dbAuthor; } – Note that if author passed in was already managed... the changes have already been queued the dbAuthor returned from the find() will be the same object as author the sets are unnecessarily changing the values of the Author to their current values

v110912Java Persistence: EntityManager27 (optional!)Potential Utiltity Class package ejava.examples.dao.jpa; import java.util.HashMap; import java.util.Map; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class JPAUtil { private static final Map factories = new HashMap (); public static EntityManagerFactory getEntityManagerFactory(String puName) { EntityManagerFactory emf = factories.get(puName); if (emf == null) { synchronized(factories) { emf = factories.get(puName); if (emf == null) { emf = Persistence.createEntityManagerFactory(puName); factories.put(puName, emf); } return emf; } public static void close() { synchronized(factories) { for(String puName : factories.keySet()) { factories.get(puName).close(); } factories.clear(); }

IndicThreads.com Java Meet June 2006