EJB 3.0 Persistence Sang Shin Java Technology Architect

Slides:



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

Copyright ©2010 Oracle Corporation Made available under Creative Commons Attribution-Share Alike 3.0 Unported EclipseLink Runtime Architecture Data Source.
Persistence Jim Briggs 1. 2 Database connectivity: JDBC Java Database Connectivity An API for connecting Java programs (applications, applets and servlets)
Michael Pizzo Software Architect Data Programmability Microsoft Corporation.
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.
Introduction to EJB INFORMATICS ENGINEERING – UNIVERSITY OF BRAWIJAYA Eriq Muhammad Adams J
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.
Data Access Patterns. Motivation Most software systems require persistent data (i.e. data that persists between program executions). In general, distributing.
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.
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.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
1 J2EE Components. 2 Application Servers relieve the programming burden for business distributed components. They provide support for system level services.
J2EE Part 2: Enterprise JavaBeans CSCI 4300 Images and code samples from jGuru EJB tutorial,
Entity Beans BMP Celsina Bignoli
© D. Wong  Indexes  JDBC  JDBC in J2EE (Java 2 Enterprise Edition)
EJB Framework.  As we know, EJB is the center of the J2EE architecture that provides a sturdy framework for building enterprise applications. The major.
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.
Introduction to Entities
Hitachi Consulting IOUG Collaborate ‘08 EJB 3.0 Java Persistence API (JPA) with Oracle TopLink Bill Lyons Systems Architect Hitachi Consulting
Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.
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 Persistence in Java Enterprise Container Managed Persistence Application Managed Persistence Michael Brockway Sajjad Shami CG0165: Advanced Applications.
Object-Relational Mapping with Hibernate Brian Sam-Bodden Principal Partner Integrallis Software, LLC. August 1 - 5, 2005.
1 Transactions Michael Brockway Sajjad Shami CG0165: Advanced Applications Development in Java Northumbria University School of Computing, Engineering.
MCS 270 Spring 2014 Object-Oriented Software Development.
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.
JBoss Fundamentals with JBuilder: Session #3110 Ken Sipe Code Mentor, Inc. Nov. 5, 2005.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
The Java Persistence API ©SoftMoore ConsultingSlide 1.
Java Persistence API part 1 INFORMATICS ENGINEERING – UNIVERSITY OF BRAWIJAYA Eriq Muhammad Adams J
Introduction to EJB. What is an EJB ?  An enterprise java bean is a server-side component that encapsulates the business logic of an application. By.
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
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.
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.
CS 440 Database Management Systems Stored procedures & OR mapping 1.
Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan Java Annotation Lesson 1.
1 EJB 3.0: There’s Something Different About You Martin Jäkle, TSBU Middleware.
Enterprise Java Beans. Contents  Understanding EJBs  Practice Section.
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
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
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:

EJB 3.0 Persistence Sang Shin Java Technology Architect

2 Agenda EJB 3.0 Persistence Requirements EJB 3.0 Programming Model Entity Life-cycle & Entity Manager Detached Entities Entity Relationships Demo: EJB 3.0 Persistence using NetBeans Enterprise Pack O/R Mapping Entity Listeners Query GlassFish

EJB 3.0 Persistence Requirements

4 Simplification of the persistence model Light-weight persistence model > In terms of programming and deployment model as well as runtime performance Testability outside of the containers > Create test clients that would use entities in a non-managed environment Domain modelling through inheritance and polymorphism Object/Relational (O/R) mapping Extensive querying capabilities

5 Common Java Persistence Between J2SE and J2EE Environments Persistence API expanded to include use outside of EJB container Evolved into “common” Java persistence API > You can use new Java persistence API in Java SE, Web, and EJB applications Support for pluggable, third-party persistence providers

EJB 3.0 Programming Model

7 EJB 3.0 Persistence Programming Model Entity is a POJO (Plain Old Java Object) Use of Annotation to denote a POJO as an entity is an annotation // It annotates Employee POJO class to be public class Employee { // Persistent/transient fields // Property accessor methods // Persistence logic methods }

8 Persistence Entity public class Customer { private Long id; private String name; private Address address; private Collection orders = new HashSet(); public Customer() public Long getID() { return id; } protected void setID (Long id) { this.id = id; }... Annotated as “Entity” Getters/setters to access denotes primary key

9 Persistence Entity Example (Contd.)... // Relationship between Customer and public Collection getOrders() { return orders; } public void setOrders(Collection orders) { this.orders = orders; } // Other business methods... }

10 Client View: From Stateless Session public class OrderEntry { // Dependency injection of Entity Manager for // the given persistence 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 }

11 Animal Entity public class Animal implements Serializable String name; String kind; String = GenerationType.AUTO) private Long id;... Annotated as denotes primary key

12 Client Code: From Java SE Client public class AnimalController {... public String create() { EntityManager em = getEntityManager(); try { utx.begin(); em.persist(animal); utx.commit(); addSuccessMessage("Animal was successfully created."); } catch (Exception ex) {... } em.close(); return "animal_list"; }

Entity Life-cycle

14 Entity Lifecycle

Entity Manager Controls Life-cycle of Entities

16 EntityManager Similar in functionality to Hibernate Session, JDO PersistenceManager, etc. Controls lifecycle of entities > persist() - insert an entity into the DB > remove() - remove an entity from the DB > merge() - synchronize the state of detached entities > refresh() - make sure the persistent state of an instance is synchronized with the values in the datastore

17 Persist Operation public Order createNewOrder(Customer customer) { Order order = new Order(customer); // Transitions new instances to managed. On the // next flush or commit, the newly persisted // instances will be inserted into the datastore. entityManager.persist(order); return order; }

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

19 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); }

Detached Entities

21 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

O/R Mapping

23 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

24 Simple Mappings CUSTOMER @Lob public class Customer { int id; String name; int c_rating; Image photo; }

25 public class Customer { int id; String name; int c_rating; Image photo; } CUSTOMER IDNAMECREDIT PHOTO

26 O/R schema="EMPLOYEE_SCHEMA") uniqueConstraints= "EMP_NAME"})} public class EMPLOYEE nullable=false, length=30) public String getName() { return name; protected int getVersionNum() { return public Address getAddress() { return address; }

27 Practice Exercise Develop a Web App that allows user manage course type A. List all of course types. B. Add course type C. Delete Course type D. Update Course type Note: You must use EJB to develop your web application.

Entity Listeners

29 Entity Listeners Listeners or callback methods are designated to receive invocations from persistence provider at various stages of entity lifecycle Callback methods > Annotate callback handling methods right in the entity class or put them in a separate listener class > Annotations > PrePersist / PostPersist > PreRemove/ PostRemove > PreUpdate / PostUpdate > PostLoad

30 Entity Listeners: Example public class AccountBean implements Account { Long accountId; Integer balance; boolean preferred; public Long getAccountId() {... } public Integer getBalance() {... context public boolean isPreferred() {... } public void deposit(Integer amount) {... } public Integer withdraw(Integer amount) throws NSFException {... }

31 Entity Listeners: Example – public void validateCreate() { if (getBalance() < MIN_REQUIRED_BALANCE) throw new AccountException("Insufficient balance to open an account"); public void adjustPreferredStatus() { preferred =(getBalance() >= AccountManager.getPreferredStatusLevel()); }

32 Entity Listeners: Example – 3 public class AlertMonitor public void newAccountAlert(Account acct) { Alerts.sendMarketingInfo(acct.getAccountId(), acct.getBalance()); }

Entity Relationships

34 Entity Relationships Models association between entities Supports unidirectional as well as bidirectional relationships > Unidirectional relationship: Entity A references B, but B doesn't reference A Cardinalities > One to one > One to many > Many to one > Many to many

35 Entity Relationships: Example Many to public class Project { private Collection public Collection getEmployees() { return employees; } public void setEmployees(Collection employees) { this.employees = employees; }... }

36 Cascading Behavior Cascading is used to propagate the effect of an operation to associated entities Cascading operations will work only when entities are associated to the persistence context > If a cascaded operation takes place on detached entity, IllegalArgumentException is thrown Cascade=PERSIST Cascade=REMOVE Cascade=MERGE Cascade=REFRESH Cascade=ALL

Entities Inheritance

38 Entity Inheritance Mapping Classes to Tables Use Java™ application metadata to specify mapping Support for various inheritance mapping strategies > Single table > All the classes in a hierarchy are mapped to a single table > Root table has a discriminator column whose value identifies the specific subclass to which the instance represented by row belongs > Table per class > Each class in a hierarchy mapped to a separate table and hence, all properties of the class (incl. inherited properties) are mapped to columns of this table > Joined subclass > The root of the hierarchy is represented by a single table > Each subclass is represented by a separate table that contains fields specific to the subclass as well as the columns that represent its primary key(s)

39 Inheritance @Inheritance(strategy=SINGLE_TABLE, discriminatorType=STRING, discriminatorValue=”CUST”) public class public class ValuedCustomer extends Customer{...}

Query

41 EJB-QL Enhancements Bulk update and delete operations Group By / Having Subqueries Additional SQL functions > UPPER, LOWER, TRIM, CURRENT_DATE,... Polymorphic queries Support for dynamic queries in addition to named queries or static queries

42 Polymorphic Queries All Queries are polymorphic by default > That is to say that the FROM clause of a query designates not only instances of the specific entity class to which it explicitly refers but of subclasses as well select avg(e.salary) from Employee e where e.salary > This example returns average salaries of all employees, including subtypes of Employee, such as Manager.

43 Joins Adds keyword JOIN in EJB-QL Supports > Inner Joins > Left Joins/Left outer joins > Fetch join > Enables pre-fetching of association data as a side-effect of the query SELECT DISTINCT c FROM Customer c LEFT JOIN FETCH c.orders WHERE c.address.state = 'MA'

44 Dynamic Queries // Build and execute queries dynamically at runtime. public List findWithName (String name) { return em.CreateQuery ( “SELECT c FROM Customer c” + “WHERE c.name LIKE :custName”).setParameter(“custName”, name).setMaxResults(10).getResultList(); }

45 Named Queries // Named queries are a useful way to create reusable name=“findCustomersByName”, queryString=“SELECT c FROM Customer c” + “WHERE c.name LIKE :custName” public EntityManager em; List customers = em.createNamedQuery(“findCustomersByName”).setParameter(“cust Name”, “smith”).getResultList();

Transactions

47 Transactions Local as well as XA transactions supported Entity managers define support for either JTA or local transactions at the time of entity manager factory creation JTA entity managers > Used in Java EE i.e. Managed environments > Container-managed entity managers must support JTA Local entity managers > EntityTransaction API can be used for application-controlled local transactions

48 Transactions public class ShoppingCartImpl implements ShoppingCart EntityManager em; public Order getOrder(Long id) { return em.find(Order.class, id); } public Product getProduct(String name) { return (Product) em.createQuery ("select p from Product p where p.name = :name").setParameter("name", name).getSingleResult(); }

49 Transactions – Example public LineItem createLineItem(Order order, Product product, int quantity) { LineItem li = new LineItem(order, product, quantity); order.getLineItems().add(li); em.persist(li); return li; } A good example, where we could have used Cascade=PERSIST, REMOVE to avoid making explicit call to em.persist(li)

50 Embedded used to mark an embeddable object Embeddable object is stored as intrinsic part of an owning entity > Shares identity of that identity; doesn't have its own identity Each persistent field/property of embeddable object is mapped to a database table

51 Embedded Objects – public class EmploymentPeriod { java.util.Date startDate; java.util.Date endDate; public EmploymentPeriod getEmploymentPeriod() {... }

52 Primary Keys and Entity Identity Simple or composite primary key must be serializable Composite key support > Primary key class must be defined to represent composite key > Can use embedded class as a primary key class > Composite key class is then mapped to a field/property or fields/properties of the entity class

Demo: EJB 3.0 Persistence Programming using GlassFish & NetBeans Enterprise Pack

54 Demo Scenario Building Web application which uses Java Persistence API Create Animal and Pavilion Entity classes that reflect ANIMAL and PAVILION database tables Create JSF page that access the database tables through Animal and Pavilion Entity classes

55 Demo Scenario Build OrderSystem application > EJB module > Web module EJB module > Item entity class > Order entity class > ProcessOrder session class > Order and Items have One to Many relationship Web module > JSF application invokes ProcessOrder session bean

GlassFish: The Next Generation Sun Java System App Server with Java EE 5 (EJB 3.0 Persistence) Support

57 GlassFish Project Supports Java EE 5 > EJB 3.0 persistence > Oracle donated TopLink code Being developed as open source project

58 Project GlassFish – How Does It Work? Community contributions encouraged! > Commit privileges to qualified developers Download with CVS Configure and build with Maven Use NetBeans (optional) > To create Java EE applications > To build GlassFish

Summary, Resources, Sun Developer Network

60 Simplifies persistence model Supports Light-weight persistence model Support both J2SE and J2EE environments Extensive querying capabilities EJB 3.0 Persistence Summary

61 Resources Glassfish persistence homepage > Persistence support page > persistence-support.html Blog on using persistence in Web applications > va_pers.html Blog on schema generation > _table_generation_feature_in

62 Technical articles Sun Developer Network Increasing developer productivity with: Empowering the Developer Tutorials and sample codes Monitored forum support Community involvement through user groups, events, and conferences And more...

63 SDN Expert Developer Help ● Project Lifeguard > Sun Developer Network Beta Program providing expert developer help > Pilot limited in scope starting November 15, Beta program can end without notice > Products supported during beta: > Java Studio Creator > Java Studio Enterprise (December 2005) > J2SE 1.4/2.5 Core > Sun Studio 10 and 11 for Solaris (December 2005) > Per incident, online help > 24 hour acknowledgment, M-F, 9-5 Bangalore TMZ > Provides help with programming “how to”

Questions?

65 EJB 3.0 Persistence Programming Model Entity is a POJO (Plain Old Java Object) Use of Annotation to denote a POJO as an entity is an annotation // It annotates Employee POJO class to be public class Employee { // Persistent/transient fields // Property accessor methods // Persistence logic methods }