EJB 3.0 Persistence Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.

Slides:



Advertisements
Similar presentations
EJB Entity Beans. Entity Beans Data versus logic Used to represent an instance rather than a collection of data (depending on underlying storage) Represents.
Advertisements

Entities and Persistence. Entity Beans Topics to be Covered: Entities are POJOs Managed/Unmanaged Entities Persistence Unit EntityManager Basic Relational.
Chapter 15 - Creating More Complex Database Applications 1 Chapter 15 Creating More Complex Database Applications.
Discover, Master, InfluenceSlide 1 SQL Server Compact Edition and the Entity Framework Rob Sanders Readify.
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.
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.
Page 1 ISMT E-120 Desktop Applications for Managers Introduction to Microsoft Access.
REFACTORING Lecture 4. Definition Refactoring is a process of changing the internal structure of the program, not affecting its external behavior and.
Maven for building Java applications By Nalin De Zoysa
LINQ Boot Camp ADO.Net Entity Framework Presenter : Date : Mahesh Moily Nov 26, 2009.
Database Programming in Java Corresponds with Chapter 32, 33.
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,
EJB Entity Beans “Modeling your data”.
Entity Beans BMP Celsina Bignoli
Middleware Technology (J2EE/EJB) Entity Bean. 2 Introduction to Entity Beans Persistence Concepts Entity beans are persistent objects that can be stored.
Introduction to Accounting Information Systems
© D. Wong  Indexes  JDBC  JDBC in J2EE (Java 2 Enterprise Edition)
Container-Managed Persistence (CMP) Entity Beans Lesson 3A / Slide 1 of 42J2EE Server Components Objectives In this lesson, you will learn to: Identify.
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.
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
Topic : JPA Kaster Nurmukan. Overview of JPA EntityManager.
Hibernate Persistence. What is Persistence Persist data to database or other storage.  In OO world, persistence means persist object to external storage.
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.
1 Transactions Michael Brockway Sajjad Shami CG0165: Advanced Applications Development in Java Northumbria University School of Computing, Engineering.
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)
Topic : Hibernate 3:Advanced ORM Kaster Nurmukan.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Programming Logic and Design Fourth Edition, Comprehensive Chapter 16 Using Relational Databases.
Enterprise Java v041109Container Managed Relationships1 Container Managed Relationships (CMR) Source: “Enterprise JavaBeans, 3rd Edition”, Richard Monson-Haefel.
Class Builder Tutorial Presented By- Amit Singh & Sylendra Prasad.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
Entity Beans & Persistence Chris Alexander CS 486 Spring 2001.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Session Beans Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0.
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.
Java Persistence API (JPA) Relationships. Kinds of relationships UML associations and aggregations (ER non- identifying relationships, shared semantics)
Mapping Objects ↔Relational DB. The Problem with Databases Databases store data in rows in tables, which are not like objects. We can simulate object.
Programmation des Applications Internet Internet Application Programming © - Last update: Friday, 05 February
13 Copyright © 2004, Oracle. All rights reserved. Managing Persistent Data in the Business Tier Entity EJBs.
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,
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.
Introduction to Database Programming with Python Gary Stewart
CS6320 – Java Persistence API
Chengyu Sun California State University, Los Angeles
Advanced Java Programming
JDBC.
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
Objectives In this lesson you will learn about: Need for servlets
Knowledge Byte In this section, you will learn about:
Chengyu Sun California State University, Los Angeles
Objectives In this lesson, you will learn about:
Presentation transcript:

EJB 3.0 Persistence Based on: Patel, Brose, Silverman, Mastering Enterprise JavaBeans 3.0

Object-Relational Mapping Relational Databases are the most common way to store persistent data  data is stored as a set of Relational Tables A mapping between Objects and data in Tables is needed  programs create and use objects There is a multitude of Relational Database Management Systems (RDMS)  the Java Database Connectivity (JDBC) API is a standard relational database access interface allows a consistent access across RDMSs

Object-Relational Mapping Clients Table Client String name Date birthdate Account account JDBC Common Mapping A Class corresponds to 1 or more Tables Class instances correspond to Rows in Tables Field values correspond to cells Accounts Table Mapping needs to maintain correspondance when saving instances and reading instances ends-up very complex and hard for maintainance

EJB 3.0 Persistence API High-level API for Object-Relational Mapping  on top of JDBC Persistent entities manipulated are Plain Old Java Objects (POJO) refered to as entities  correspondance to Relational Tables is ensured by the API  frees away from lot of low level tasks

Entities Plain Old Java Object In-memory Java representation of persistent data  loaded from storage with fields populated with the stored data  can be modified in memory to change the value of data  can be saved back (updates the database data) Uses Annotations introduced in Java SE 5.0 (J2SE 1.5.0)

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

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

Entities An entity class must declare a primary key using  entity objects of the same class are uniquely identified by the primary key Access to the entity's persistent can be by direct field access or using JavaBean style of getters and setters An entity can add more methods (business methods)

Persistence Context Set of entity instances in which for any persistent entity identity there is a unique entity instance. Entity instances are managed within a persistence context by a particular Entity Manager. The scope of context can either be a transaction (e.g. a request), or an extended unit of work (e.g. a session)

Entity Manager Used to access database and control lifecycle of entities A Persistence Unit defines the set of entity types that can be managed by a given entity manager  defines the set of all classes that are related or grouped by the application, and which must be collocated in their mapping to a single data store Two types of Entity managers  Container-Managed Entity Manager  Application-Managed Entity Manager

Entity Manager -API  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 data store  find() - find entities by their primary key  flush() - immediately synchronize entity and DB

Entity Manager 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; }

Entity Manager 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); }

Entity Manager 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); }

Entity Manager Container-Managed Entity Manager  The lifecycle of the Entity Manager is managed by the container  Can be obtained by: Injection from container From SessionContext using lookup() method

Entity Manager Container-Managed Entity Manager obtained by injection from Container public class... { /** Entity manager object, injected by container private EntitityManager manager;... private Account findAccount(int accountNumber) { Account account = manager.find(Account.class,accountNumber); return account; }... } Instance is provided by Container

Entity Manager Container-Managed Entity Manager obtained from session public class... { public void service ( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Context envCtx = new InitialContext().lookup("java:comp/env"); EntityManager em = (EntityManager) envCtx.lookup("persistence/logicalName");... Account account = manager.find(Account.class,accountNumber);... }... }

Entity Manager Application-Managed Entity Manager  The lifecycle of the Entity Manager is managed by the application  Entity Manager created using a EntityManagerFactory  Entity Manager needs to be closed by application

Application-Managed Entity Manager public class RegistrationServlet extends HttpServlet { // EntityManagerfactory private EntityManagerFactory emf; public void service ( HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Entity Manager creation EntityManager manager = emf.createEntityManager();... Account account = manager.find(Account.class,accountNumber);... // close Entity Manager manager.close(); }... }

Entity Lifecycle

New: entity created in memory but not associated yet with a persistent entity in database Managed: entity has a persistent identity in the database and is associated with a persistent context. Detached: entity has a persistent identity but is no longer associated with the persistent context. Removed: entity is associated with a persistent context but has been scheduled for removal from the database.

Object-Relational Mapping Comprehensive set of annotations defined for mapping  Relationships  Joins  Database tables and columns  Database sequence generators ... Specified using standard description elements in a separate mapping file or within the code as annotations

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

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

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

Mapping Inheritance hierarchies Specifies Tables correspondence to Classes with sub-classing  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  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)

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

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

Entity Relationships One-to-one – exactly one entity related to another entity (e.g. Person and SIN Card) One-to-many – an entity is related to many other entities (e.g. Manager and Employee) Many-to-one – many entities related to a particular entity (e.g. Bank Account and Person) Many-to-many – many entities related to many entities (e.g. Student and Course)

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

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

Queries Entity Manager method find() returns a managed Entity from an item in the Database based on a provided primary key public static User findUser(EntityManager em,String id) { User u = em.find(User.class, id); return u; }

Queries Query object is used for other queries General steps for making queries with Query object  obtain instance of Query from Entity Manager  customize query object if necessary (e.g. setting query parameters, upper limit of result set size,...)  execute query Queries can be expressed in  EJB-QL: object query language using Query method createQuery(String query)  SQL: standard Relational Database language using Query method createNativeQuery(String query)

Queries public static List findUsersByName(EntityManager em,String name) { // create EJB-QL query Query query = em.createQuery( "SELECT u FROM User u" + " WHERE u.NAME = :userName"); // customize query query.setParameter("userName",name); // run query List resultList = query.getResultList(); return resultList; }

Named Queries Queries that are defined in a static way  possibility to invoke throughout the code  provide a single point (name=”findThem”, queryString=”Select a FROM Account a”) public class Account implements Serializable {...}... public class.. // use of named query within persistence unit public List listAccounts() { Query query = manager.createNamedQuery(“findThem”); return query.getResultList(); }

Transactions Enable to group multiple operations into a single unit  either the whole group succeed or  the whole group fails if something goes wrong Transaction support is essential for safe, consistent Database updates UserTransaction provides interface for setting and controlling Transactions:  begin() - begin a new transaction  commit() - complete a transaction  rollback() - abord a transaction and go back to initial state

Transactions public class LookupServlet extends HttpServlet { // injects a User Transaction private UserTransaction utx;... public boolean addUser() { try { utx.begin(); User nuser = new User(); nuser.setUSER_ID(..); nuser.setNAME(...); nuser.setBIRTHDATE(...); manager.persist(nuser); utx.commit(); return true; } catch (Exception ex) { utx.rollback() } return false; }