Title: Distributed Objects: Enterprise JavaBean and Object Persistence
1Distributed ObjectsEnterprise JavaBean and
Object Persistence
- Jianguo Lu
- University of Windsor
2Outline
- Distributed object
- EJB concepts
- Components, JavaBean
- Backgrounds of EJB multi-tier application,
distributed objects, middleware. - EJB roles, EJB varieties.
- Object persistence
- Simple mapping
- Mapping aggregation
- Mapping inheritance
3Part 1 Distributed Objects and EJB
4Distributed objects
- Distributed computing part of the system located
on separate computers - Distributed objects allow objects running on one
machine to be used by client applications on
different computers - Distributed object technologies
- Java RMI
- CORBA
- DCOM
5Implementing distributed objects
Distributed object
client
Remote interface
Remote interface
stub
Skeleton
network
- Stub client side proxy object
- Skeleton server side proxy object
- Stub and skeleton implements the same remote
interface
6Write your own distributed object
- Client only knows the interface
- public interface Person
- public int getAge() throws Throwable
- public String getName() throws Throwable
-
- Client uses the object just as if it were local
- public class PersonClient
- public static void main(String args)
- try
- Person person new Person_Stub()
- int age person.getAge()
- String name person.getName()
- System.out.println(name age)
- catch (Throwable t)
-
-
-
- Networking is taken care of by Person_Stub
7From the client side
- public class Person_Stub implements Person
- Socket socket
- public Person_Stub() throws Throwable
- socketnew Socket(ip address here",
8765) -
-
- public int getAge()throws Throwable
- ObjectOutputStream outStream
- new
ObjectOutputStream(socket.getOutputStream()) - outStream.writeObject("age")
- outStream.flush()
- ObjectInputStream inStream
- new
ObjectInputStream(socket.getInputStream()) - return inStream.readInt()
-
- public String getName()throws Throwable
8From the server side
- public class Person_Skeleton extends Thread
- public void run()
- ServerSocket serverSocket new
ServerSocket(8765) - Socket socket serverSocket.accept()
- while (socket ! null)
- ObjectInputStream inStream new
ObjectInputStream(socket.getInputStream()) - String method (String) inStream.readObject(
) - if (method.equals("age"))
- int age myServer.getAge()
- ObjectOutputStream outStream
- new ObjectOutputStream(sock
et.getOutputStream()) - outStream.writeInt(age)
- outStream.flush()
- else if (method.equals("name"))
-
-
- public static void main(String args)
- PersonServer person new PersonServer("mike",
24) - Person_Skeleton skelnew Person_Skeleton(perso
n)
9- public class PersonServer implements Person
- int age
- String name
- public PersonServer(String n, int a) namen
agea - public int getAge() return age
- public String getName() return name
10From hand-craft to RMI
- RMI technology
- Automatically generate appropriate stubs and
skeletons - Error and exception handling
- Parameter passing
- RMI is not good enough in
- Object persistence
- Transaction handling
- Security
-
11Explicit Middleware
Transfer(Account a1, Account a2, long amount)
Call middleware API to check security call
middleware API to start a transaction
subtract the balance of a1 and add the amount to
a2 call DB API to store the data call
middleware API to end the transaction
- Difficult to write, maintain, and support
12Implicit middleware
Transaction API
Transaction service
client
security API
Remote interface
Security service
Remote interface
stub
Skeleton
Database driver
DB API
implicit middleware
network
Transfer(Account a1, Account a2, long amount)
subtract the balance of a1 and add the amount to
a2
Declare the middle services needed in a text
file. Generate a RequestInterceptor from this
declaration
- Easy to write, maintain, and support
13EJBs intent
- EJB wants to provide basic services and
environment to make enterprise systems easier to
develop. - EJB provides automatically-managed persistence
logic - EJB provides transactioning plumbing for
components - EJB provides an enforced-authorization framework
- EJB provides "best of breed" capabilities by
providing all this in a vendor-neutral fashion
14Persistence Management
- Perform all state and persistence management
under the control of the application server - Access to relational data is done through SQL
- Most Java programmers aren't great database
engineers - Therefore let the application server worry about
how to obtain the data
EmployeeBean
name
sal
findByName()
SELECT FROM EMP WHERE NAME?
SAL
NAME
Emp
15Opaque Transactional Plumbing
- Transactionally execute all actions to prevent
inconsistency - Despite our best programmatic efforts, sometimes
things will go wrong. - Asking programmers to deal with all the possible
right/wrong combinations is a recipe for
disaster. - Data integrity still remains the highest priority
- Let the app server track the success or failure,
and commit or rollback as necessary.
16Security Framework
- Ensure that only authorized clients can perform
sensitive actions - Certain operations (or resources) are sensitive
- Not all users should have access to those
sensitive operations or resources - As a result, the system needs to enforce
authorization rights - We can give the app server knowledge of what
principals have what rights - Therefore let the app server deal with the
enforcement of authorization policy by checking
roles of callers (either declaratively or
programmatically)
17What is EJB (Enterprise JavaBean)
- Enterprise
- n. (In computer industry) an organization that
uses computers. - Could be corporations, businesses, government
bodies. - The organization is often large rather than
small. - adj. large, distributed (information system).
- JavaBean
- Independent reusable software component
- Extend the write once, run anywhere to reuse
anywhere - Enterprise JavaBean
- The architecture for a server-side platform that
provides distributed components
18Components
- Components
- Reusable software building block.
- Objects with additional capabilities that enable
them to function in large-scale information
system. - Easy to combine with other components.
- Components live in containers.
- Example GUI widgets such as a button.
- A container is an application program in which
component is run - Example Browser, MS word, IDE (Integrated
Development Environment)
19JavaBeans components
- JavaBean is Sun's component architecture for the
Java application environment. - Visual programming tools can combine beans to
create an application. - A bean implements an additional set of interfaces
from an ordinary Java object. The interfaces
specific to a bean are - Introspection - Allows a visual programming tool
to analyze how a bean works, allowing developers
to connect beans. - Customization - Enables developers to customize
the appearance and behavior of a bean, using a
property sheet provided by a visual programming
tool. - Events - Enables beans to communicate by using a
notification mechanism. - Properties - Describes the bean's attributes and
broadcasts a notification when an attribute
changes. - Persistence - Allows developers to customize
beans and package them into a Java Archive (JAR)
file. Also known as serialization.
20Enterprise JavaBean
- The architecture for a server-side platform that
provides distributed components - EJB is different from JavaBean
- Client-side? Server Side
- Standalone? distributed
- Need to take care of transaction etc.
21Multi-tier Enterprise Architecture
Database 1
Browser 1
Application server 1
Legacy application
Web server
Browser 2
Application server 2
Browser 3
Tier 3
Tier 4
Tier 1
Tier 2
22EJB architecture
Enterprise Information System (RDBMS)
EJB container/server
Client application
Enterprise bean
Enterprise Information System (ERP)
Web container
Browser
Enterprise bean
JSP
- EJB Servers examples
- Websphere Application Server
- WebLogic
- Web Servers examples
- Apache tomcat
-
23Roles in EJB system
- Enterprise Bean Provider
- Produce and sell EJBs such as CourseBean
- Domain expert (such as expert in course ware)
- Do not need to take care of system level
programming such as transaction, security, and
distribution. - Application Assembler
- Uses EJB to build an application
- Business process expert (such as a domain expert
in XYZ Training Co) - E.g., a student should register a course after
made a payment - Deployer/System Administrator
- Expert in a specific operational environment
(such as the system admin in XYZ Co) - EJB Server Provider/EJB Container
Provider/Persistence Manager Provider - Take care of the transactions, security,
persistency etc. - System expert (such as IBM, Sun, BEA)
24Roles in EJB (cont.)
EJB Container server persistent Manager
Provider
EJB client application
EJB server container
Application assembler
Database
Enterprise JavaBean provider
System admin
EJB Deployer
25Types of EJBs
EmployeeBean
Entity Bean
name
sal
findByName()
SELECT FROM EMP WHERE NAME?
CMP
BMP
Stateless
stateful
SAL
NAME
BMP Bean Managed Persistency CMP Container
Managed Persistency Entity Beans were replaced by
the Java Persistence API in EJB 3.0.
Emp
26Session Bean and Entity Bean
27Part 2 Object Persistency
28Object Persistency
- Persistency characteristic of data that outlives
the execution of the program that created it. - A persistent object is one that can automatically
store and retrieve itself in permanent storage. - Objects can't be directly saved to and retrieved
from relational databases. - Approaches to object persistency
- Object serialization
- Convert object into a byte stream and store it as
a whole in database/ file system. - Object database
- Objects are the 1st class citizen in the database
- Object relational mapping (ORM)
- Supported by Hibernate, EJB, etc.
29Relational model vs. object model
from www.agiledata.org
30Objects and relations
31Mapping objects (Entity beans) to Tables
- Simple case
- Map entities to tables
- Map attributes (with primitive data types) in an
entity bean to columns in the table - Synchronizing the object with the table is taken
care of by EJB container
EmployeeBean
ID
name
sal
findByName(n) SELECT FROM EMP WHERE NAMEn
- ejbLoad
- SELECT name, sal FROM employee WHERE id?
- ejbStore
- UPDATE employee SET name?, sal? WHERE id?
- ejbPostCreate
- INSERT INTO employee VALUES(?,?,?)
- ejbRemove
- DELETE FROM employee WHERE id?
SAL
NAME
ID
Employee Table
32Object attributes and table columns
- Not all attributes are mapped to table columns
- Describe the mapping using deployment descriptor
using XML (or using annotation in EJB3.0)
ltenterprise-beansgt ltentitygt
ltejb-namegtEmployeelt/ejb-namegt
ltcmp-fieldgt name lt/cmp-fieldgt
ltcmp-fieldgt sal lt/cmp-fieldgt
lt/entitygt lt/enterprise-beansgt
- What if the attribute in an entity bean is an
entity bean itself? - E.g., Employee bean may have Address attribute
- It is a relations between objects
33Relationships between objects
- Aggregation
- Mapping strategies
- Single table aggregation
- Foreign key aggregation
- Manage cardinalities
- Manage many-to many relations
- Manage composition
- Inheritance
- One table for one inheritance tree
- One table for one class
- One table for one inheritance path
34Single Table Aggregation Pattern(1/4)
- Abstract map aggregation to a relational data
model by integrating all aggregated objects
attributes into a single table. - Example CourseEdition has Instructor attribute
- Design pattern a general repeatable solution to
a commonly-occurring problem in software design
CourseEdition
EndDate String
StartDate String
Code String
instructor Instructor
course Course
Instructor
Type Integer
SSN Integer
surName String
Age Integer
townOfBirth String
name String
35Single Table Aggregation(2/4)
- Solution Put the aggregated object's attributes
into the same table as the aggregating objects.
36Single Table Aggregation(3/4)
CourseEdition
EndDate String
CourseEditionTable
StartDate String
Code String
instructor Instructor
EndDate VARCHAR(0)
course Course
StartDate VARCHAR(0)
Code VARCHAR(0)
course VARCHAR(0)
Type SMALLINT
SSN SMALLINT
Instructor
surName SMALLINT
Age SMALLINT
Type Integer
townOfBirth SMALLINT
SSN Integer
surName String
Age Integer
townOfBirth String
name String
37Single Table Aggregation(4/4)
- Consequences
- Performance
- Pro only one table needs to be accessed to
retrieve an aggregating object with all its
aggregated objects. - Con the fields for aggregated objects
attributes are likely to increase the number of
pages retrieved with each database access,
resulting in a possible waste of I/O bandwidth. - Maintenance and flexibility If the aggregated
object type is aggregated in more than one object
type, the design results in poor maintainability
as each change of the aggregated type causes an
adaptation all of the aggregating object types
database tables. - Consistency of the database Aggregated objects
are automatically deleted on deletion of the
aggregating objects. - Ad-hoc queries If you want to form a query that
scans all Instructor objects in the database,
this is very hard to formulate.
38Foreign Key Aggregation (1/3)
- Abstract The pattern shows how to map
aggregation to a relational data model using
foreign keys. - Solution Use a separate table for the aggregated
type. Insert an synthetic object identity into
the table and use this object identity in the
table of the aggregating object to make a foreign
key link to the aggregated object.
AggregatingTable
aggregatedObjectID
attribute1
Foreign key
AggregatedObjectTable
ObjectID
attribute1
39Foreign Key Aggregation (2/3)
- Example Instructor and CourseEdition are mapped
to two tables
CourseEdition
(from OM_Training)
CourseEditionTable
EndDate String
StartDate String
Code String
instructor Instructor
EndDate VARCHAR(8)
course Course
StartDate VARCHAR(8)
Code VARCHAR(8)
course VARCHAR(8)
instructorID VARCHAR(8)
Instructor
InstructorTable
(from OM_Training)
Foreign key
Type Integer
Type SMALLINT
SSN Integer
SSN SMALLINT
surName String
surName VARCHAR(8)
Age Integer
Age SMALLINT
townOfBirth String
townOfBirth VARCHAR(8)
name String
instructorID VARCHAR(8)
40Foreign Key Aggregation (3/3)
- Consequences
- Performance Foreign Key Aggregation needs a join
operation or at least two database accesses where
Single Table Aggregation needs a single database
operation. If accessing aggregated objects is a
statistical rare case this is acceptable. If the
aggregated objects are always retrieved together
with the aggregating object, you have to have a
second look at performance here. - Maintenance Factoring out objects like
Instructor into tables of their own makes them
easier to maintain and hence makes the mapping
more flexible. - Consistency of the database Aggregated objects
are not automatically deleted on deletion of the
aggregating objects. - EJB container helps maintain the consistency of
CMP entity bean. BMP entity bean will need
additional code to maintain consistency. - Ad-hoc queries Factoring out aggregated objects
into separate tables allows easy querying these
tables with ad-hoc queries.
41Specify relations using deployment descriptor
ltenterprise-beansgt ltentitygt
ltejb-namegtCourseEditionlt/ejb-namegt
lt/entitygt ltentitygt
ltejb-namegtInstructorlt/ejb-namegt
lt/entitygt lt/enterprise-beansgt
CourseEdition
EndDate String
StartDate String
Code String
instructor Instructor
course Course
1
1
ltejb-relationgt ltejb-relation-namegtInstructor-C
ourseEditionlt/ejb-relation-namegt
ltejb-relationship-rolegt
ltejb-relationship-role-namegt Instructor-For
lt/ejb-relationship-role-namegt
ltmultiplicitygtOnelt/multiplicitygt
ltrelationship-role-sourcegt ltejb-namegt Instructor
lt/ejb-namegt lt/relationship-role-sourcegt
lt/ejb-relationship-rolegt ltejb-relationship-ro
legt ltejb-relationship-role-namegt
Courses lt/ejb-relationship-role-namegt
ltmultiplicitygt One lt/multiplicitygt
ltrelationship-role-sourcegtltejb-namegt
CourseEdition lt/ejb-namegtlt/relationship-role-sourc
egt lt/ejb-relationship-rolegt lt/ejb-relationgt
Instructor
Type Integer
SSN Integer
surName String
Age Integer
townOfBirth String
name String
42Manage Cardinality 1 to many relationships
CourseEdition
ltejb-relationgt ltejb-relation-namegtInstructor
-CourseEditionlt/ejb-relation-namegt
ltejb-relationship-rolegt
ltejb-relationship-role-namegt Instructor-For
lt/ejb-relationship-role-namegt
ltmultiplicitygt Many lt/multiplicitygt
ltrelationship-role-sourcegt ltejb-namegt Instructor
lt/ejb-namegt lt/relationship-role-sourcegt
lt/ejb-relationship-rolegt ltejb-relationship-r
olegt ltejb-relationship-role-namegt
Courses lt/ejb-relationship-role-namegt
ltmultiplicitygt One lt/multiplicitygt
ltrelationship-role-sourcegt ltejb-namegt
CourseEdition lt/ejb-namegt
lt/relationship-role-sourcegt ltcmr-fieldgt
ltcmr-field-namegt courses lt/cmr-field-namegt
ltcmr-field-typegt
java.util.Collection lt/cmr-field-typegt
lt/cmr-fieldgt lt/ejb-relationship-rolegt
lt/ejb-relationgt
EndDate String
StartDate String
Code String
instructor Instructor
course Course
n
1
Instructor
Type Integer
SSN Integer
surName String
Age Integer
townOfBirth String
name String
43Manage cardinality many to many relationships
- Example A Trainee may register several
CourseEditions, and one CourseEdition has a
number of Trainees. - Solution Create a separate table containing the
object identifiers (or Foreign Keys) of the two
object types participating in the association.
Map the rest of the two object types to tables
using any other suitable mapping pattern.
ltejb-relationgt ltejb-relation-namegt
Trainee-CourseEditionlt/ejb-relation-namegt
ltejb-relationship-rolegt
ltejb-relationship-role-namegt Trainee-EnrollIn-Cour
ses lt/ejb-relationship-role-namegt
ltmultiplicitygt Many lt/multiplicitygt
ltrelationship-role-sourcegt ltejb-namegt Instructor
lt/ejb-namegt lt/relationship-role-sourcegt
ltcmr-fieldgt ltcmr-field-namegt courses
lt/cmr-field-namegt
ltcmr-field-typegt java.util.Collection
lt/cmr-field-typegt lt/cmr-fieldgt
lt/ejb-relationship-rolegt
ltejb-relationship-rolegt
ltejb-relationship-role-namegt Courses-HaveEnrolle
d-Trainees lt/ejb-relationship-role-namegt
ltmultiplicitygt Many lt/multiplicitygt
ltrelationship-role-sourcegt ltejb-namegt
CourseEdition lt/ejb-namegt lt/relationship-role-sour
cegt ltcmr-fieldgt ltcmr-field-namegt
trainees lt/cmr-field-namegt
ltcmr-field-typegt java.util.Collection
lt/cmr-field-typegt lt/cmr-fieldgt
lt/ejb-relationship-rolegt lt/ejb-relationgt
44Object aggregation and composition
- Aggregation and composition
- Composition is a stronger form of aggregation.
- In composition, when deleting the owning objects,
the contained object will also be deleted. - In UML, composition relation is drawn as filled
diamond, while aggregation as unfilled diamond. - Examples
- When a car is destroyed, so is its carburetor.
When a pond is destroyed, the ducks are still
alive. - When a university closes, the departments will be
closed as well. However, data about professors
should still be there.
45Manage composition in EJB 2.0
- Use cascaded delete in deployment descriptor, to
indicate that deletion operation on Instructor is
cascaded down to associated Telephone objects. - ltejb-relationgt
- ltejb-relation-namegtInstructor-Telephonelt/ejb
-relation-namegt - ltejb-relationship-rolegt
- ltmultiplicitygtOnelt/multiplicitygt
- ltrelationship-role-sourcegt ltejb-namegt
Instructor lt/ejb-namegt lt/relationship-role-source
gt - lt/ejb-relationship-rolegt
- ltejb-relationship-rolegt
- ltmultiplicitygtManylt/multiplicitygt
ltcascade-delete/gt - ltrelationship-role-sourcegt ltejb-namegt
Telephone lt/ejb-namegt lt/relationship-role-sour
cegt - lt/ejb-relationship-rolegt
- lt/ejb-relationgt
46Mapping inheritance
- Strategies of mapping inheritance to tables
- One table for the inheritance tree
- One table for each class
- One table for each inheritance path
47One table for the inheritance tree
- Solution use the union of all attributes of all
objects in the inheritance hierarchy as the
columns of a single database table.
Base class instance DescendantA
instance DescendantB instance
48One table for the inheritance tree
- Consequences
- Write/update performance Reading/writing any
objects in the hierarchy with one database
operation - Space consumption Requires more space to store
the objects
49One table for each class
- Solution
- Map the attributes of each class to a separate
table
DescendentA Table
DescendentA Attributes
50One table for each class
- Consequences
- Write and update performance More database
operations involved - Space consumption has near optimal consumption
- Maintenance cost As the mapping is
straightforward and easy to understand, schema
evolution is straightforward and easy.
51One table for each inheritance path
- Solution
- Map the attributes of each class to a separate
table. To a classs table add the attributes of
all classes the class inherits from. - If BaseClass is abstract, BaseClassTable is not
generated.
52One table for each inheritance path
- Consequences
- Write and update performance One database
operation to read or write an object - Space consumption No redundant attributes
- Maintenance cost Adding or deleting attributes
of a superclass results in changes to the tables
of all derived classes.