Beruflich Dokumente
Kultur Dokumente
BHUPESH RAVISH
Project Engineer
CDAC, Mumbai
1
CDAC, Mumbai
Agenda
Introduction
Motivation for EJB 3.0
Java 5.0 Annotations
Types of Beans
Container Services
Interceptors
2
CDAC, Mumbai
Introduction
EJB 3.0 is the next revision of the Enterprise Java Beans
specification. One of the most significant changes in EJB
3.0 is the introduction of a standard O/R mapping
specification and the move to POJO based persistence.
3
CDAC, Mumbai
Sun Microsystems’s Definition for EJB
4
CDAC, Mumbai
Motivation
EJB 2.1 technology very powerful, but too
complex
– Too many classes, interfaces
– Awkward environment lookups (JNDI APIs)
– Boilerplate javax.ejb interface methods
– Clumsy programming model
– Deployment descriptors
5
CDAC, Mumbai
Java 5.0 Annotations
annotations do not directly affect program semantics
can be inspected through source parsing or by using the
additional reflection APIs
define custom annotations
– annotate fields, methods, classes, etc.
used to define
– bean's business interface
– O/R mapping information (specific persistence)
– resource references
– deployment information
EJB 3.0 makes extensive use of annotations to replace
XML
6
CDAC, Mumbai
EJB 3.0 Goals
Make EJB easier to learn and use
• Fewer classes and interfaces
• No required container interfaces
• Dependency injection
• Simple lookups
• No required deployment descriptor
• Simplified persistence
• Standardized object/relational mapping
7
CDAC, Mumbai
EJB 3.0 Approach
Simplification of the EJB APIs
9
CDAC, Mumbai
Simplification of EJB Bean Types
Business interfaces are plain Java interfaces
• No more required EJBObject/EJBLocalObject
interfaces
Home interfaces are no longer needed
• No more required EJBHome/EJBLocalHome
interfaces
• Only need business interface, not home
Annotations for (optional) callback methods
• No more required javax.ejb.EnterpriseBean
interfaces
Dependency injection, simple lookup method
• No more need to use JNDI APIs
10
CDAC, Mumbai
Example // EJB 2.1
SessionContext ctx;
DataSource empDB;
<session>
<ejb-name>PayrollBean</ejb-name>
<local-home>com.example.PayrollHome</local-home>
<local>com.example.Payroll</local>
<ejb-class>com.example.PayrollBean</ejb-class>
<session-type>Stateful</session-type>
<transaction-type>Container</transaction-type>
<resource-ref>
<res-ref-name>jdbc/empDB</res-ref-name>
<res-ref-type>javax.sql.DataSource</res-ref-type>
<res-auth>Container</res-auth>
</resource-ref>
</session>
…
<assembly-descriptor>
…
</assembly-descriptor>
14
CDAC, Mumbai
Same Example // EJB 3.0
@Stateful
public class PayrollBean implements Payroll {
@Resource DataSource empDB;
public void setBenefitsDeduction (int empId, double
deduction) {
Connection conn = empDB.getConnection();
…
}
}
@Remote
public interface Payroll {
public void setBenefitsDeduction (int empId, double
deduction);
}
15
CDAC, Mumbai
EJB 3.0: XML Deployment Descriptor
17
CDAC, Mumbai
Types of Beans
Session Beans
Entity Beans
18
CDAC, Mumbai
Session Bean
Represents TaskFlow.
Fills gap left by Entity Beans
Describe interaction between other Beans
19
CDAC, Mumbai
Stateless Session Bean
20
CDAC, Mumbai
Stateless Session Beans
– Home interface
– Remote/Local interface
– Bean class must implement javax.ejb.SessionBean
– XML Deployment descriptor
21
CDAC, Mumbai
EJB 2.1: Required Interfaces
Homes for stateless beans unnecessary
Remote interface must inherit from EJBObject
Remote methods must throw RemoteException
– Dependency on RMI
23
CDAC, Mumbai
EJB 2.1: XML Deployment Descriptor
<session>
<ejb-name>CalculatorBean</ejb-name>
<home>in.cdac.CalculatorHome</home>
<bean>in.cdac.CalculatorBean</bean>
<remote>in.cdac.CalculatorRemote</remote>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
</session>
….
24
CDAC, Mumbai
EJB 3.0 interface & class
Homeless
Methods don’t throw RemoteException
No verbose interface implementations
Class.newInstance();
@PreDestroy() Injections
@PostConstrauct
Business Method
26
CDAC, Mumbai
Stateful Session Beans
Maintains client-specific session information (called
conversational state) across multiple method calls and
transactions
27
CDAC, Mumbai
Stateful Session Beans
Still homeless
– Created as they are looked up
@Remove replaces EJBObject.remove
Stateful bean is removed after method called
@Remove
public void checkout() {
…
}
}
28
CDAC, Mumbai
EJB 3.0 Deployment Descriptor
Believe it or not, people like XML deployment
descriptors
Externalize configuration
29
CDAC, Mumbai
Simplified Client View
Session beans have plain Java business interface
• Looks like normal Java interface to client
• Access can be local or remote (as specified)
30
CDAC, Mumbai
Example // EJB 2.1
…
Context initialContext = new InitialContext();
initialContext.lookup(“java:comp/env/ejb/cart”);
31
CDAC, Mumbai
Example: EJB 3.0 Client View
…
@EJB ShoppingCart myCart;
…
Collection widgets = myCart.startToShop(“widgets”);
OR
32
CDAC, Mumbai
Where Did the Home Interface Go?
Stateless Session Beans
• Home interface not needed anyway
• EJB 2.1 Home.create() didn’t really create
• Container creates or reuses pooled bean instance when business
method is invoked
• Can use new SLSB class with “legacy” Home (and no
extra code)
33
CDAC, Mumbai
Dynamic Lookup
Dynamic lookup is simplified as well
35
CDAC, Mumbai
LifeCycle of a stateful session bean
Class.newInstance()
timeout
@PreDestroy() Injections
@PostConstruct()
36
CDAC, Mumbai
Entity Beans
37
CDAC, Mumbai
Goals of Entity Beans
38
CDAC, Mumbai
Defining Entity Beans
39
CDAC, Mumbai
Entity Annotations
@Entity
@Table(name=“AUCTION_ITEM”)
public class Item {
@Id(generate=GeneratorType.AUTO)
@Column(name=“ITEM_ID”)
public long getId() {
return id;
}
40
CDAC, Mumbai
Entity Annotations
@Entity
@Table(name=“AUCTION_ITEM”) create table AUCTION_ITEM
public class Item { (
private long id; ITEM_ID Number,
private String description; DESC varchar(255),
private String productName; ProductName varchar(255),
private User seller; USER_ID Number
);
@Id(generate=GeneratorType.AUTO)
@Column(name=“ITEM_ID”)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
41
CDAC, Mumbai
Entity Annotations
@Entity
@Table(name=“AUCTION_ITEM”) create table AUCTION_ITEM
public class Item { (
private long id; ITEM_ID Number,
private String description; DESC varchar(255),
private String productName; ProductName varchar(255),
private User seller; USER_ID Number
);
@Id(generate=GeneratorType.AUTO)
@Column(name=“ITEM_ID”)
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
42
CDAC, Mumbai
Entity Annotations
@Column(name=“DESC”,
nullable=false, length=500) create table AUCTION_ITEM
public String getDescription() { (
return description; ITEM_ID Number,
} DESC varchar(500),
public void setDescription(String ProductName varchar(255),
desc) { OWNER_ID Number
this.description = desc; );
}
public String getProductName() {
return productName;
}
protected void
setProductName(String name) {
this.productName = name;
}
43
CDAC, Mumbai
Relationships
Relationships
– @ManyToOne, @OneToOne, @OneToMany,
@ManyToMany
– Supports lazy and eager loading of
relationships
– Cascades: delete, create, and merge
– No CMR: You must manage the
relationships somewhat.
44
CDAC, Mumbai
Entity Relationships
@OneToOne(fetch=LAZY)
@Column(name=“OWNER_ID”)
public Owner getOwner() {
return owner;
}
@OneToMany(cascade=ALL)
@JoinColumn(name=“ITEM_ID”)
protected Set<Bid> getBids() {
return bids;
}
protected void setBids(Set<Bid> bids) {
this.bids = bids;
}
45
CDAC, Mumbai
Entity Relationships
@OneToOne(fetch=LAZY)
@Column(name=“OWNER_ID”) create table AUCTION_ITEM
(
public Owner getOwner() {
ITEM_ID Number,
return owner; DESC varchar(255),
} ProductName varchar(255),
protected void setOwner(Owner OWNER_ID Number
user) { );
this.owner = owner;
} @OneToMany(cascade=ALL) create table BID
@JoinColumn(name=“ITEM_ID”) (
…
protected Set<Bid> getBids() {
ITEM_ID Number
return bids; …
} );
protected void setBids(Set<Bid>
bids) {
this.bids = bids;
}
46
CDAC, Mumbai
Multi-Table
Multi-Table Mappings,
– Entity can be stored in one or
more tables
– @SecondaryTables,
@SecondaryTable
47
CDAC, Mumbai
Multi-table Mappings
@Entity
@Table(name=“OWNER”)
@SecondaryTable(name=“ADDRESS” create table OWNER
join={@JoinColumn(name=“ADDR_ID”) (
}) OWNER_ID Number,
public class Owner { NAME varchar(255),
private long id; );
private String name;
private String street; create table ADDRESS
private String city; (
private String state; ADDR_ID Number,
@Id(generate=GeneratorType.AUTO) STREET varchar(255),
@Column(name=“OWNER_ID”) CITY varchar(255),
public long getId() { STATE varchar(255)
return id; );
}
public void setId(long id) {
this.id = id;
} 48
CDAC, Mumbai
Multi-table Mappings
…
@Column(name=“STREET”,
secondaryTable=“ADDRESS”) create table OWNER
public String getStreet() { (
return street; OWNER_ID Number,
} NAME varchar(255),
public void setStreet(String street) { );
this.street = street;
} create table ADDRESS
(
@Column(name=“CITY”, ADDR_ID Number,
secondaryTable=“ADDRESS”) STREET varchar(255),
public String getCity() { CITY varchar(255),
return city; STATE varchar(255)
} );
protected void setCity(String city) {
this.city = city;
}
49
CDAC, Mumbai
Interacting With Entity Bean
50
CDAC, Mumbai
Entity Manager
EntityManager is the central service for all persistence actions.
Entities are plain java objects that are allocated just like any other
Java object. They do not become persistent until your code
explicitly interacts with the EntityManager to make them persistent.
51
CDAC, Mumbai
Entity Manager
All entities persisted by the EntityManager service
– All access through this service
– Creation, retrieval, removal, and merging
– Analogous to Hibernate Session
52
CDAC, Mumbai
EntityManager
@Stateless public class ItemImpl implements ItemRemote {
@PersistenceContext(unit name=“item”)
EntityManager entityManager;
53
CDAC, Mumbai
Persistence Context
A persistence context is a set of managed entity object
instances.
There are two types of persistence contexts:
4. Transaction-scoped persistence context
5. Extended persistence context
54
CDAC, Mumbai
Persistence Context contd.
@PersistenceContext(unit name=“titan”)
EntityManager entityManager;
@TransactionAttribute(REQUIRED)
public Customer someMethod() {
Customer cust = entityManager.find(Customer.class,1);
cust.setName(“new name”);
return cust;
}
55
CDAC, Mumbai
Persistence Context contd.
56
CDAC, Mumbai
Persistence Context contd.
@PersistenceContext(unitName=“titan”,
type=PersistenceContextType.Extended)
private EntityManager extendedManager;
….
Customer cust = null;
transaction.begin(); //start tranasaction 1
cust = extendedManager.find(Customer.class,1);
tranasction.commit(); // tranasaction 1 ends
57
CDAC, Mumbai
Create the objects
58
CDAC, Mumbai
Packaging a Persistence Unit
An example of persistence.xml fle :
<persistence>
<persistence-unit name=“item”>
<jta-data-source>java:/OracleDS</jta-data-source>
<properties>
<property name=“org.hibernate.hbm2ddl”>update</property>
</properties>
</persistence-unit>
</persistence>
The JAR file of the persistence unit may also optionally contain a
mapping XML DD called orm.xml in the META-INF directory of
the deployment. This file used to define the mapping between the
classes container in the persistence
unit and the database to which they map.
59
CDAC, Mumbai
EntityManagerFactory
In Java SE, entity managers are created using
javax.pesistence.EntityManagerFactory.
60
CDAC, Mumbai
Interacting with an EntityManager
The EntityManager API has methods to insert and remove entities
from a database as well as merge, updates from detached enity
instances.
public interface EntityManager {
public void persist(Object entity); // from new to managed
public <T> T merge(T entity); // from detached to managed
public void remove(Object entity); // from managed to removed
public Object find(String entityName,
Object primaryKey); // find by primary key
public <T> T find(Class entityClass,
Object primaryKey); // --´´--
public void flush(); // sync to database
public Query createQuery(String ejbqlString); // create EJB-QL query
public Query createNamedQuery(String name); // named queries
public Query createNativeQuery(String sqlString); // create SQL query (not
portable)
public void refresh(Object entity); // sync from database
...
}
61
CDAC, Mumbai
Inheritance
62
CDAC, Mumbai
Inheritance – SINGLE_TABLE
@Entity
@Table(name="Animal") create table Animal
@Inheritance(strategy=InheritanceType. (
SINGLE_TABLE) ID Number,
@DiscriminatorColumn(name="TYPE") TYPE varchar(255),
public class Animal {
@Id private int id; AVG_WEIGHT Number,
@Column(name="AVG_WEIGHT") BREED varchar(255)
private int averageWeight; );
...
}
@Entity
@Inheritance(strategy=InheritanceType.
SINGLE_TABLE)
public class Dog extends Animal{
@Column(name="BREED")
private String breed;
...
}
63
CDAC, Mumbai
Inheritance – JOINED
@Entity
@Inheritance(strategy=InheritanceType.JOINED) create table Animal
@Table(name="Animal") (
public class Animal{ ID Number,
@Id private int id; TYPE varchar(255),
@Column(name="AVG_WEIGHT") AVG_WEIGHT Number
private int averageWeight; );
...
}
create table Doggy
@Entity (
@InheritanceJoinColumn(name="DOGY_ID") DOGGY_ID Number,
@Table(name="Doggy") BREED varchar(255)
public class Dog extends Animal{ );
@Column(name="BREED")
private String breed;
...
}
64
CDAC, Mumbai
Inheritance – UNION
@Entity
@Inheritance(strategy=InheritanceType.TABLE_P create table Animal
ER_CLASS) (
@Table(name="Animal") ID Number,
public class Animal{ TYPE varchar(255),
@Id private int id; AVG_WEIGHT Number
@Column(name="AVG_WEIGHT")
private int averageWeight; );
...
} create table Doggy
(
@Entity DOGGY_ID Number,
@InheritanceJoinColumn(name="DOGY_ID") BREED varchar(255)
@Table(name="Doggy") );
public class Dog extends Animal{
@Column(name="BREED")
private String breed;
...
}
65
CDAC, Mumbai
Query API
Java interface that is obtained at runtime from Entity Manager
Queries may be expressed as EJBQL strings
– Embedded in code
– Externalized to metadata (named queries)
Invoke via Query interface
– Named parameter binding
– Pagination control
66
CDAC, Mumbai
EJB QL 3.0
68
CDAC, Mumbai
Entity Callbacks & Listeners
PrePersist
PostPersist
PostLoad
PreUpdate
PostUpdate
PreRemove
PostRemove
69
CDAC, Mumbai
Message-driven Beans
70
CDAC, Mumbai
Message-driven Beans
71
CDAC, Mumbai
JMS Messaging Models
Topic
Publisher Topic
Topic
72
CDAC, Mumbai
JMS Messaging Models
Potential
Reciever
Sender Queue
Potential
Reciever
Point-to-Point ( 1 -> 1 )
73
CDAC, Mumbai
Basics of JMS
Message Producer
Message Consumer
Message Type
74
CDAC, Mumbai
JMS Programming Model
Connection Factory
creates
Connection
creates
Session creates
creates
creates
Message Consumer Message Consumer
Sends to Sends to
Msg
Destination Destination
75
CDAC, Mumbai
Example
Just implements MessageListener
@MessageDriven( activationConfig={
@ActivationConfigProperty(
propertyName=“destinationType”,
propertyValue=“javax.jms.queue”)})
Class.newInstance()
@PreDestroy() Injections
@postConstruct
Method-Ready
Pool
Business
methods
77
CDAC, Mumbai
Timer Service
@Timeout
Public void maintainence(javax.ejb.Timer timer){
…..
}
78
CDAC, Mumbai
Container Services: Transactions
What is a Transaction ?
– Unit of Work.
– Set of Activities.
Must be having ACID properties, viz. Atomic,
Consistent, Isolated, Durable
In EJB 3.0 we have Declarative Transaction
Management.
Transaction management
• Container-managed transaction (CMT) by default
• Bean-managed transaction (BMT) by annotation
79
CDAC, Mumbai
Transactions contd.
Container-managed transactions
• REQUIRED transaction attribute by default
• Any transaction attribute by annotation
Specified at class level => applies to all business
methods of the class
Specified at method level => applies to method
(overriding any class-level specification)
• Typical case (CMT + REQUIRED) is default
80
CDAC, Mumbai
Example
@Stateless public class PayrollBean implements Payroll {
@TransactionAttribute(REQUIRED)
public void setBenefitsDeduction (int empId, double
deduction) {…}
@TransactionAttribute(REQUIREDNEW)
public void setSalary(int empId, double salary) {…}
…
}
81
CDAC, Mumbai
Container Services: Security
Security configuration typically done at deployment
• Developer can provide guidance
Security attributes
• If not specified => set on deployment or
“unchecked”
• Method permissions by annotation
Specified at class level => applies to all business
method of class
Specified at method level => applies to method
(overriding any class-level specification)
@PermitAll, @RolesAllowed
Use caller principal by default
• Run-as principal by annotation
82
CDAC, Mumbai
Example
// Security view
@Stateless public class PayrollBean implements Payroll
{
public void setBenefitsDeduction (int empId, double
deduction) {…}
@RolesAllowed(“HR_PayrollAdministrator”)
public void setSalary(int empId, double salary) {…}
…
}
83
CDAC, Mumbai
Container Services: Event Notification
Container calls bean upon lifecycle events
• @PostConstruct
• @PreDestroy
• @PrePassivate
• @PostActivate
Bean specifies events it needs to know about
• Removes boilerplate code, “magic methods”
ejbCreate, ejbRemove, etc
Callback methods can be specified on separate
interceptor class or on bean class
PostConstruct and PreDestroy annotations
adopted into JSR-250 (“Common Annotations”)
84
CDAC, Mumbai
Example
@Stateful public class AccountManagementBean
implements AccountManagement {
Socket cs;
@PostConstruct
@PostActivate
private void initRemoteConnectionToAccountSystem ()
{
…
}
@PreDestroy
@PrePassivate
private void closeRemoteConnectionToAccountSystem
() {
…
}
}
85
CDAC, Mumbai
Interceptors
Powerful facility for more advanced developers.
86
CDAC, Mumbai
Interceptors contd.
Default interceptors
• Specified in deployment descriptor
Lack of application-level metadata annotation facility
Apply to all business methods of components in ejb-jar
Class-level interceptors
• Apply to all business method of bean class
Method-level interceptors
• Apply to specific business method only
High degree of control available
• Can specify exactly which interceptors in hierarchy
get invoked for a given class or method
• Ability to exclude default interceptors and/or classlevel
interceptors
87
CDAC, Mumbai
Example
@Interceptors({
in.cdac.AccountAudit.class,
in.cdac.Metrics.class,
in.cdac.CustomSecurity.class
})
@Stateless public class AccountManagementBean
implements AccountManagement {
…
public void createAccount (int accountId, Details details)
{…}
public void deleteAccount (int accountId) {…}
public void activateAccount (int accountId) {…}
public void deactivateAccount (int accountId) {…}
…
}
88
CDAC, Mumbai
Example
public class AccountAudit{
@AroundInvoke
public Object auditAccount (InvocationContext inv)
throws Exception{
try {
Object result = inv.proceed();
return result;
} catch (Exception ex) {
throw ex;
}
……
}
}
89
CDAC, Mumbai
Summary
Major simplification of EJB for developers
• Bean is plain Java class with plain Java
business interface
• Injection model for services and resources
• Removal of boilerplate code
• Elimination of need for deployment descriptors
EJB 3.0 components interoperate with existing
applications
Gives developer simple-to-use and powerful
capability
90
CDAC, Mumbai
Questions
91
CDAC, Mumbai
bhupesh@cdacmumbai.in
ravishbhupesh@gmail.com
92
CDAC, Mumbai