Middleware Technology (J2EE/EJB) Entity Bean (JBoss EJB 3.0 tutorial)

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.
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.
Object Persistence and Object-Relational Mapping James Brucker.
Introduction to JPA Java Persistence API Introduction to JPA.
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.
Object and object-relational databases 1. Object databases vs. Object-relational databases Object databases Stores complex objects – Data + functions.
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.
Introduction –All information systems create, read, update and delete data. This data is stored in files and databases. Files are collections of similar.
JPA Java Persistence API. Introduction The Java Persistence API provides an object/relational mapping facility for managing relational data in Java applications.
NHibernate in Action Web Seminar at UMLChina By Pierre Henri Kuaté 2008/08/27
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.
CHAPTER 14 USING RELATIONAL DATABASES TO PROVIDE OBJECT PERSISTENCE (ONLINE) © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database.
EJB 3.0 Persistence Sang Shin Java Technology Architect
Introduction to Entities
Object Oriented Analysis and Design 1 Chapter 7 Database Design  UML Specification for Data Modeling  The Relational Data Model and Object Model  Persistence.
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 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.
Topic : Hibernate 2: Object Persistence and ORM Kaster Nurmukan.
Java Data Persistence Using Hibernate Jack Gardner October 2004.
JPA / HIBERNATE CSCI 6370 Nilayan Bhattacharya Sanket Sable.
Java Persistence API v1.0 a standard for ORM frameworks and POJO based Persistence Magnus Larsson
Topic : Hibernate 3:Advanced ORM Kaster Nurmukan.
Fall CIS 764 Database Systems Engineering L18.2 : Object Relational Mapping … ….Object persistence.
Topic : Hibernate 1 Kaster Nurmukan. An ORM tool The problem fixed by ORM Advantage Hibernate Hibernate Basic –Hibernate sessionFactory –Hibernate Session.
1 Nov 29, 2005 Object Relational Mapping Frameworks Wiene Höweler.
The Java Persistence API ©SoftMoore ConsultingSlide 1.
Object storage and object interoperability
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)
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,
Hibernate Thuy, Le Huu. Pentalog VN. Agenda Hibernate Annotations Improving performance – Lazy loading – Fetching Strategies – Dynamic insert, dynamic.
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.
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.
Hibernate Annotation 李日貴 (jini) jakarta99 AT gmail.com SoftLeader Tech. Corp. Taiwan Java Annotation Lesson 1.
Introduction to Database Programming with Python Gary Stewart
1 EJB 3.0: There’s Something Different About You Martin Jäkle, TSBU Middleware.
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
Java Data Persistence Using Hibernate
Database Applications (15-415) ORM - Part I Lecture 11, February 11, 2018 Mohammad Hammoud.
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:

Middleware Technology (J2EE/EJB) Entity Bean (JBoss EJB 3.0 tutorial)

2 Entity Beans Entity beans represent (persistent) data Every application has data –It is often the case that this data naturally exists as objects e.g. In a Banking application: Account, Customer, Transaction –Applications need a way to map these objects to their database (often an RDBMS) They can write code themselves (e.g. JDBC) They can use an Object-Relational Mapping (ORM) framework

3 Object-Relational Mapping (ORM) There are several ORM frameworks available for Java: –Hibernate (JBoss) –TopLink (Oracle) –ObJect-relational Bridge - OJB (Apache) –Java Data Objects – JDO (Sun) –Java Persistence (Sun) – The ORM technology used by EJB

4 Object-Relational Mapping (ORM) There are several ORM frameworks available for Java: –Hibernate (JBoss) Open source framework released by JBoss in 2001 Ported for.NET as NHibernate Uses an object-based query language called Hibernate-QL –TopLink (Oracle) –ObJect-relational Bridge - OJB (Apache) –Java Data Objects – JDO (Sun) –Java Persistence (Sun) – The ORM technology used by EJB

5 Object-Relational Mapping (ORM) There are several ORM frameworks available for Java: –Hibernate (JBoss) –TopLink (Oracle) TopLink was released by The Object People (TOP) in 1994 for SmallTalk TopLink was re-released in 1997 for Java Oracle acquired TopLink in 2002 TopLink uses expressions for querying –ObJect-relational Bridge - OJB (Apache) –Java Data Objects – JDO (Sun) –Java Persistence (Sun) – The ORM technology used by EJB

6 Object-Relational Mapping (ORM) There are several ORM frameworks available for Java: –Hibernate (JBoss) –TopLink (Oracle) –ObJect-relational Bridge - OJB (Apache) OJB is an implementation of JDO provided for free by Apache –Java Data Objects – JDO (Sun) –Java Persistence (Sun) – The ORM technology used by EJB

7 Object-Relational Mapping (ORM) There are several ORM frameworks available for Java: –Hibernate (JBoss) –TopLink (Oracle) –ObJect-relational Bridge - OJB (Apache) –Java Data Objects – JDO (Sun) An ORM standard developed by Sun (released: 2002) Can be used in any JVM Use an object-based query language called JDO-QL –Java Persistence (Sun) – The ORM technology used by EJB

8 Object-Relational Mapping (ORM) There are several ORM frameworks available for Java: –Hibernate (JBoss) –TopLink (Oracle) –ObJect-relational Bridge - OJB (Apache) –Java Data Objects – JDO (Sun) –Java Persistence (Sun) – The ORM technology used by EJB This technology grew out of the previous technologies –Thus, it is very similar in API to the other technologies discussed The aim is to provide a transparent framework for persisting entities (that are Plain Old Java Objects – POJOs) Java Persistence uses an object-based query language called EJB-QL (also called Java Persistence Query Language)

9 Object-Relational Mapping An application has instances of classes (entities): public class Customer { private String firstName; private String lastName; … other fields omitted … } …which need to be stored in RDBMSs: FirstNameLastNameBirthDateCompanyBalance RobertSmith02/16/1956IBM SusanJones06/07/1968BEA0.00 FeliciaAlvarez12/31/1977Sun100.00

10 Java Persistence Features When using Java Persistence, the container handles: –Relationships between entities –Persistence of the entity’s data All this is in addition to the container’s responsibilities for all EJBs: –Transactions –Security

11 Entity: The Bean import javax.persistence.Entity; import public class Customer public int customerID; // primary key public String firstName; public String lastName; … other fields omitted … } annotation marks this class as an entity annotation marks the customerID field as the primary key for the entity (mapped directly to the database primary key) The data will be persisted to a table with the same name, and the fields will be persisted to columns with the same name

12 Entity: The Bean (Alternative #1) public class primaryKey=true) public int public String public String lastName; … other fields omitted … } Here, the mapped table and column names are explicitly declared This example uses public fields for the entity’s properties

13 Entity: The Bean (Alternative #2) public class primeyKey=true) public int getCustomerID() { … }; public void setCustomerID(int value) { … }; private int public String getFirstName() { … }; public void setFirstName(String value) { … }; private String firstName; … other fields omitted … } Here, the entity’s properties are accessed using get/set methods –The actual fields used can now be private, preserving 表示该字段为主键

14 Entity Clients Entity clients, since EJB 3.0, are most often session beans –Sometimes, developers create a session façade for the entity This is a session bean whose sole purpose is to act as the CRUD (Create/Read/Update/Destroy) for the entity The core of the entity client is the EntityManager –This object can be used to acquire, search for, update, create, and delete entities –An EntityManager can be injected into a session façade

15 CRUDs Objects whose purpose is to provide the following functions on an entity: –Create – Create and persist new instances of entities –Read – Find individual entities (by primary key) and search for groups of entities (querying) –Update – Modify entities (locally and in the persistent store) –Destroy – Delete entities (locally and in the persistent store) In Java EE, CRUD functions are provided by the EntityManager class

16 EntityManager: Create An entity is pretty much a POJO –It can, therefore, be created in the normal way –However, the entity is not persistent until the EntityManager is told to persist the EntityManager entityManager; public Customer createCustomer(String fn, String ln) { Customer customer = new Customer(); customer.setFirstName(fn); customer.setLastName(ln); // customer is not persistent here entityManager.persist(customer); // customer is persistent here return customer; }

17 EntityManager: Read #1 (Individual) A specific entity can be found using its primary EntityManager entityManager; public Customer getCustomer(int customerID) { return entityManager.find(Customer.class, customerID); }

18 EntityManager: Read #2 (Search) A search can be performed using a EntityManager entityManager; public List getAllCustomers() { // this query is EJB-QL, which is similar to SQL String queryString = “select c from Customer c”; Query query = entityManager.createQuery(queryString); return query.getResultList(); }

19 EntityManager: Read #3 (Search) Queries can also take EntityManager entityManager; public List getCustomersWithLastName(String lastName) { // this query is EJB-QL, which is similar to SQL String queryString = “select c from Customer c where c.lastName = :lastName”; Query query = entityManager.createQuery(queryString); query.setParameter(“lastName”, lastName); return query.getResultList(); }

20 EntityManager: Read #4 (Search) The EJB-QL is sophisticated, and has many features of SQL (e.g. group EntityManager entityManager; public List getCustomersByNameKeyword(String keyword) { // this query is EJB-QL, which is similar to SQL String queryString = “select c from Customer c where c.lastName like :keyword1 or c.firstName like :keyword2”; Query query = entityManager.createQuery(queryString); query.setParameter(“keyword1”, keyword); query.setParameter(“keyword2”, keyword); return query.getResultList(); }

21 EntityManager: Read #5 (Entity) A developer can also create named queries in the EJB itself: queryString=" select c from Customer c where c.city = ?1") }) public class primeyKey=true) public int getCustomerID() { … }; … the remainder is no different from previous versions …

22 EntityManager: Read #5 (Search) The named queries can be referenced from the client –Notice that no EJB-QL needs to be embedded in this client, which is good for EntityManager entityManager; public List getCustomersByCity(String city) { Query query = entityManager.createNamedQuery(“FindByCity”); query.setParameter(0, city); return query.getResultList(); }

23 EntityManager: Update Once an entity is persisted, it becomes managed –Changes to managed entities are automatically recorded to the persistent store –Changes will no doubt be cached for efficiency, but you can flush() an entityManager to force the changes to be carried out immediately Usually, this is unnecessary entityManager.flush(); // flush all updates The latest database data can also be retrieved into an entity, using the refresh() method: entityManager.refresh(customer1); // update customer1

24 EntityManager: Destroy The EntityManager can also be used to delete an EntityManager entityManager; public void deleteCustomer(int customerID) { Customer customer = manager.find(Customer.class, customerID); manager.remove(customer); }

25 Entity Beans Example Entity beans are not remotable and must be access through the new javax.persistence.EntityManager service. JBoss's EJB 3.0 implementation is built on top of Hibernate.

26 Order and LineItem two related Entity beans. Order and LineItem. These two beans form a one to many relationship and automatic table generation is used to generate the database tables. all getter/setter methods will be treated as persistence properties. Entity Bean = "PURCHASE_ORDER") public class Order implements java.io.Serializable persitence.xml java:/DefaultDS

27 Order Field definition private int id; private double total; private primary key public int = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="order") public Collection getLineItems() OrderLineItem 1 * Note: The mappedBy attribute specifies that this is a bi-directional relationship that is managed by the order property on the LineItem entity bean. Foreign Key

28 LineItem private = “order_id”) bi-directional, foreign key public Order getOrder() { return order; } specifies the foreign key column within the LineItem table. Note : LineItem (owner side) corresponds to the table with foreign key , while Order is the target side. There is a member variable (order) in class LineItem, which is related to the foreign key order_id in the table. Code: entity

29 JBoss Console: manage entity beans

30

31

32

33

34 Entity Detachment and Reattachment = "FIRST") public String getFirst() Find by primary key public Customer find(int id) { return manager.find(Customer.class, id); } Find by other fields public List findByLastName(String name) { return manager.createQuery("select c from Customer c where c.last = :name").setParameter("name", name).getResultList(); } Code: merge

35 ManyToMany and OneToOne Relationships Example OneToOne –Customer vs. Address ManyToMany –Customer vs. Flight

36 OneToOne Customer vs. Address class Customer (contains the foreign key field: = = "ADDRESS_ID") public Address getAddress() { return address; }

37 ManyToMany Customer vs. Flight There is a many to many relationship between Customer and Flight. In order to have a many to many relationship there needs to be a distinct join table ( 关联表 ) that maps the many to many relationship. This is called an association table. So there is no join column (foreign key) on both sides (table), and we could not distinguish the owner side from the target side. Customer = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER, mappedBy="customers") Flight = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = = "flight_customer_table"), joinColumns = = "FLIGHT_ID")}, inverseJoinColumns = = "CUSTOMER_ID")}) public Set getCustomers() { return customers; } In the above example, Flight is selected as the owner side. In the join table (flight_customer_table, FLIGHT_ID is the foreign key.

38 Dependency Injection Example Field private Calculator calculator; Set method private Calculator public void setCalculator(Calculator c) { set = c; } Note: beanName(class name), mappedName (JNDI)

39 Composite Primary Keys Example The EJB 3.0 specification allows you to define a primary key class as and use it as the primary key of your Entity bean. One or more properties can be used as members of the primary public class CustomerPK implements java.io.Serializable mapping the primary key in Customer bean public CustomerPK getPk() { return pk; }

40 Timer Service Example An EJB bean can register a timer with the EJB Timer service. In the EJB 2.1 specification it was required to implement an interface to get ejbTimeout callbacks. It is still being debated in the EJB 3.0 EG on whether an interface or annotation should be used to specify this callback. In JBoss EJB 3 Preview, it is implemented as an annotation. All you have to define is a method annotated with javax.ejb.Timeout. This is the same with other etc... No interface is needed to be implemented, just declare the methods as you need them.