Entities and Persistence. Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational.

Slides:



Advertisements
Similar presentations
11 Copyright © 2005, Oracle. All rights reserved. Creating the Business Tier: Enterprise JavaBeans.
Advertisements

JBoss Seam: Contextual Components Jason Bechtel
Introduction to Enterprise JavaBeans. Integrating Software Development Server-side Component Model Distributed Object Architecture –CORBA –DCOM –Java.
EJB Development and Support Services. EJB Development and Support Services Topics to be Covered: EJB Design Bean/Container Interaction Java Naming and.
1 Lecture 18 George Koutsogiannakis/Spring 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
The Java Persistence API Edel Sherratt. Contents Revisit applications programming Using Java Persistence API.
Java Persistence API Maciej Adamiak. Agenda -Entity, -Entity Operations, -Query Language.
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
1 Lecture 17 George Koutsogiannakis/SUMMER 2011 CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES.
1 The JNDI ENC and Injection Every EJB container that is deployed in an application server has its own personal internal registry called the Enterprise.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
1 Session Bean Chuyên đề Lập trình Java & J2EE Chương 14 Biên soạn: Th.S Nguyễn văn Lành.
J2EE Part 2: Enterprise JavaBeans CSCI 4300 Images and code samples from jGuru EJB tutorial,
Lecture 8 Advanced Topics in Enterprise JavaBeans.
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.
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
CS 160: Software Engineering November 5 Class Meeting Department of Computer Science San Jose State University Fall 2014 Instructor: Ron Mak
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.
Fall CIS 764 Database Systems Engineering L7. EJB’s.
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.
Enterprise JavaBeans Understanding EJB Components Version 0.1 Kamal Wickramanayake
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.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Creating competitive advantage Copyright © 2003 Enterprise Java Beans Presenter: Wickramanayake HMKSK Version:0.1 Last Updated:
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
Enterprise Java v041109Container Managed Relationships1 Container Managed Relationships (CMR) Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel.
08 Encapsulation and Abstraction. 2 Contents Defining Abstraction Levels of Abstraction Class as Abstraction Defining a Java Class Instantiating a Class.
EJB Overview: Constraint Types and Enforcement in JBoss Elissa Newman Fluid Meeting 6/3/04.
Entity Beans & Persistence Chris Alexander CS 486 Spring 2001.
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.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
Session Beans Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.
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.
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February
Java Programming: Advanced Topics 1 Enterprise JavaBeans Chapter 14.
13 Copyright © 2004, Oracle. All rights reserved. Managing Persistent Data in the Business Tier Entity EJBs.
JPA The New Enterprise Persistence Standard Mike Keith
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,
14 Copyright © 2004, Oracle. All rights reserved. Achieving State Management in the Business Tier.
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 Java Persistence API. What is Persistence Persistence: The continued or prolonged existence of something. Most Applications Achieve Persistence.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
©NIIT Session Beans Lesson 1B/ Slide 1 of 37J2EE Server Components Objectives In this lesson, you will learn to: Describe the characteristics of session.
CS6320 – Java Persistence API
Chengyu Sun California State University, Los Angeles
Java Persistence Architecture (JPA)
Intro To Classes Review
Advanced Java Programming
Objectives In this lesson, you will learn to:
Understanding and Designing with EJB
Topics Persistence API for JAVA EE5 Java Transaction API Entity class.
Chengyu Sun California State University, Los Angeles
CS 240 – Advanced Programming Concepts
Presentation transcript:

Entities and Persistence

Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational Mapping The Primary Key

Entities and Persistence Entities are POJOs

Entities and Persistence In Java EE 5, persistence no longer defined by EJB specification Java Persistence API –Abstraction on top of JDBC –Object-to-Relational Mapping (ORM) Engine

Entities and Persistence javax.persistence.EntityManager –Service that performs persistence actions Entity Creation Entity Update Entity Removal Entity Query –Manages ORM between entity classes and underlying data source –Tightly integrated with Java EE and EJB but not limited to this environment

POJOs Entities are plain old Java objects (POJOs) Allocated using new operator Entities do not become persistent until they are associated with an EntityManager

POJOs import public class Customer { private int id; private public int getId() { return id; } public void setId(int id) { this.id = id; }

POJOs String getName() { return name; } public void setName(String name) { this.name = name; }

POJOs Allocated instances of the Customer class remain POJOs until you ask the EntityManager to create the entity in the database The following does not create a Customer instance in the database: Customer cust = new Customer(); cust.setName(“Bill”);

Entities and Persistence Managed/Unmanaged Entities

Entity is either –managed (attached) by an entity manager Or –unmanaged (detached) Managed –EntityManager tracks state changes –Synchronizes changes to database Unmanaged –Any state changes are not tracked by EntityManager

Persistence Context Set of managed entity object instances Managed by an entity manager –Tracks all changes –Flushes changes to the database Once persistence context is closed –All managed entity object instances becomes detached –Any state changes will not be synchronized to the database

Persistence Context Transaction-scoped –Life of context as long as a transaction –Closed with a transaction completes –Application server persistence contexts EntityManager instances injected with the PersistenceContext EntityManager entityManager;

Persistence Context Transaction-scoped –Methods invoked within the context of JTA public Customer someMethod() { Customer cust = entityManager.find(Customer.class, 1); cust.setName(“new name”); return cust; }

Persistence Context Extended –Live longer than a transaction –Maintains conversation with database without the overhead of a transaction –Managed by application code and stateful session beans

Persistence Context Extended Customer cust = null; trans.begin(); cust = extendedEntityManager.find( Customer.class, 1); trans.commit(); trans.begin(); cust.setName(“Bill”); extendedEntityManager.flush(); trans.commit();

Persistence Context Detached Entities –Occurs when transaction scope or extended persistence context ends –Can be serialized and sent across the network to a remote client –Client can make changes and send them back to server to be merged back and synchronized with the database –Persistent objects become value objects when they are detached from a persistent context

Entities and Persistence Persistence Unit

A fixed set of classes mapped by an EntityManager to a particular database Defined in a persistence.xml file –Required deployment descriptor for Java Persistence specification Set of classes may be specified or persistence provider can scan JAR file to identify classes –Classes scanned annotation Tied to only one data source

Persistence Unit java:/OracleDS update

Entities and Persistence EntityManager

Obtaining an EntityManager Java SE (and less frequently in Java EE) –Use an EntityManagerFactory –createEntityManager() returns EntityManager instances that manage an extended persistence context –Remember to close() the EntityManagerFactory

Obtaining an EntityManager Use static createEntityManagerFactory() method of javax.persistence.Persistence class EntityManagerFactory factory = Persistence.createEntityManagerFactory (“CRM”); ……… factory.close();

Obtaining an EntityManager Now to get an EntityManager, use createEntityManager() method of EntityManagerFactory class Returned EntityManager represents an extended persistence context Must explicitly enlist EntityManager instance into JTA-enabled transactions using the joinTransaction() method

Obtaining an EntityManager Java EE –Use EntityManager injection public class MySessionBean implements MySessionRemote private EntityManager entityManager; ……… }

Obtaining an EntityManager The unitName attribute identifies the persistence unit A transaction-scoped persistence context is injected by default Never call close() on an injected EntityManager

Interacting with an EntityManager Persisting Entities (INSERT) –Allocate an instance of entity –Set its properties –Wire up relationships with other entities –Interact with EntityManager service Customer cust = new Customer(); cust.setName(“Bill”); entityManager.persist(cust);

Interacting with an EntityManager Finding Entities (SELECT) –Locate by Primary Key –find() method –Returns null if entity is not found –Initializes state Customer cust = entityManager.find(Customer.class, 2);

Interacting with an EntityManager Finding Entities (SELECT) –Locate by Primary Key –getReference() method –Throws EntityNotFoundException if entity is not found –State not guaranteed Customer cust = null; try{ cust = entityManager.getReference(Customer.class, 2); } catch(EntityNotFoundException e) { //recovery logic }

Interacting with an EntityManager Finding Entities (SELECT) –Locate by Querying –EJB QL Query query = entityManager.createQuery(“from Customer c where id=2”); Customer cust = (Customer)query.getSingleResult();

Interacting with an EntityManager Updating Entities (UPDATE) –After locating an entity and prior to closing the persistence context –Change the state of the entity –Wire up relationships with other entities –Interact with EntityManager service // Same active persistence context Cabin cabin = entityManager.find(Cabin.class, id); cabin.setBedCount(newCount)

Interacting with an EntityManager Merging Entities –Merges state changes made to a detached entity back into persistent storage –Scenario: Remote client finds an object in the database using a session bean method Object detached from entity manager, serialized, and returned to the remote client Client makes changes to detached object, and sends the object back to the server using a session bean method Method takes updated object and merges it into the current persistence context using merge() method public void updateCabin(Cabin cabin) { Cabin copy = entityManager.merge(cabin); }

Interacting with an EntityManager Merging Entities –If no Cabin instance with the same ID currently being managed, a managed copy is returned by merge() method –If Cabin instance with the same ID currently being managed, contents of parameter are copied into managed instance, and a managed instance is returned by merge() method. –In both cases above, the parameter remains detached and unmanaged public void updateCabin(Cabin cabin) { Cabin copy = entityManager.merge(cabin); }

Interacting with an EntityManager Removing Entities (DELETE) –After locating an entity and prior to closing the persistence context –Remove the entity –After remove() is invoked, instance will no longer be managed (it becomes detached) // Same active persistence context Cabin cabin = entityManager.find(Cabin.class, id); entityManager.remove(cabin);

Interacting with an EntityManager refresh() –Refreshes state of entity from the database contains() –Takes entity instance as a parameter –Returns true if instance is currently being managed by the persistence context clear() –Detaches all managed entity instances from the current persistence context

Interacting with an EntityManager flush() –Changes made when calling persist(), merge(), and remove() are not synchronized with the database until the entity manager decides to flush –flush() forces synchronization to occur

Entities and Persistence Basic Relational Mapping

Mapping Persistent Objects Entities –Model business concepts that can be expressed as nouns –Describe both the state and behavior of real-world objects –Represent data in the database –Provide a simple mechanism for accessing and changing data –Provide opportunities for software reuse Persistence –The process of coordinating the data represented by a bean instance with the database –Java persistence specification provides a portable object-to-relational mapping (ORM)

Programming Model Summary Entities are POJOs Interact with entity manager service to persist, update, remove, locate, and query entities –Enrolls entity in transactions –Persists state to database

An Entity Must have a no-argument annotation denotes the class should be mapped to a annotation marks which property will be used as the primary key All other properties map to a column of the same name and type Table name default to the unqualified name of the entity

An Entity Example package edu.weber.domain; import javax.persistence.*; import public class Customer implements Serializable { private long id; private String firstName; private String public long getId() { return id; } public void setId(long id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String fn) { this.firstName = fn; } public String getLastName() { return lastName; } public void setLastName(String ln) { this.lastName = ln; } }

Corresponding Table Definition create table Customer ( id long primary key not null, firstName VARCHAR(255), lastName VARCHAR(255) );

Elementary Assume a different table definition from before create table CUSTOMER_TABLE ( CUST_ID integer primary key not null, FIRST_NAME VARCHAR(20) not null, lastName VARCHAR(255) not null );

Elementary Schema Specifies the relational table the bean class public class Customer implements …………

Elementary Schema Specifies how a particular field or property is mapped to a column in nullable=false, columnDefinition=“integer”) public long getId() { return id; } public void setId(long id) { this.id = id; length=20, nullable=false) public String getFirstName() { return firstName; } public void setFirstName(String fn) { this.firstName = fn; public String getLastName() { return lastName; } public void setLastName(String ln) { this.lastName = ln; }

Entities and Persistence The Primary Key

Primary Key Overview Uniquely identifies an entity Can be any serializable type –Primitive type –Primitive wrappers (Integer, Double, etc.) –java.lang.String –Custom Classes composed of the above Single-Field (or Property) Primary Key –Map to a single persistence field Compound Primary Key –Custom-defined object whose instance variables map to several persistence fields

Single-Property Primary Keys Map to one of the entity’s persistence Identifies one (or more) properties that make up the primary public long getId() { return id; } public void setId(long id) { this.id = id; }

@GeneratedValue(strategy=GenerationType.AUTO) public long getId() { return id; } public void setId(long id) { this.id = id; }

Compound Primary Keys Map to one or more of the entity’s persistence fields Implemented by a custom class –Must be serializable –Define equals() and hashcode() methods –Instance fields must correspond to entity’s persistence fields in both name and type –Public no-argument constructor required

Compound Primary Key Example public class CustomerPK implements java.io.Serializable { private String lastName; private long ssn; public CustomerPK() { } public CustomerPK(String lname, long ssn) { this.lastName = lname; this.ssn = ssn } // …getters and setters… public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof CustomerPK)) return false; CustomerPK pk = (CustomerPK)obj; if(!lastName.equals(pk.lastName) || ssn != pk.ssn) return false; else return true; } public int hashCode() { return lastName.hashCode() + (int)ssn; } }

Annotating the @IdClass(CustomerPK.class) public class Customer implements Serializable { private String firstName; private String lastName; private long ssn; public String getFirstName() { return firstName; } public void setFirstName(String fn) { this.firstName = fn; public String getLastName() { return lastName; } public void setLastName(String ln) { this.lastName = ln; public long getSsn() { return ssn; } public void setSsn(long ssn) { this.ssn = ssn; } }

Querying the Customer CustomerPK pk = new CustomerPK(“Burke”, ); Customer cust = entityManager.find(Customer.class, pk);

Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational Mapping The Primary Key