CDAC, Mumbai1
An Introduction to EJB 3.0An Introduction to EJB 3.0
BHUPESH RAVISHProject EngineerCDAC, Mumbai
CDAC, Mumbai2
AgendaAgenda
IntroductionMotivation for EJB 3.0Java 5.0 AnnotationsTypes of BeansContainer ServicesInterceptors
CDAC, Mumbai3
Introduction 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.
One of the principal goals of EJB 3.0 is:“Simplification of object persistence by the definition of a light-weight object/relational mapping facility based on the direct use of Java classes rather than persistent components.”
JSR 220: Enterprise JavaBeansTM,Version 3.0
EJB 3.0 Simplified API
CDAC, Mumbai4
Sun Microsystems’s Definition for EJBSun Microsystems’s Definition for EJB
The Enterprise JavaBeans architecture is a component architecture for the java development and deployment of component based distributed business applications. Application written using EJB are scalable, transactional and multi-user secure. These applications may be written once and then can be deployed on any server platform that supports EJB Specifications.
CDAC, Mumbai5
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
CDAC, Mumbai6
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
CDAC, Mumbai7
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
Improve developer productivity
CDAC, Mumbai8
EJB 3.0 Approach
Simplification of the EJB APIs
• Removal of need for EJBHomes and EJBObjects• Removal of JNDI APIs from developer and client view• Removal of need for deployment descriptors
Use advantages of Java language metadata
• Metadata designed so that the most common cases are easiest to express• Defaults available for expected cases
CDAC, Mumbai9
EJB 3.0 Approach contd.
More work is done by container, less by developer
Contracts now benefit developer rather than container• Bean specifies what it needs through metadata No longer written to unneeded container interfaces• Container interpositions and provides requested services to bean
CDAC, Mumbai10
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.EnterpriseBeaninterfaces
Dependency injection, simple lookup method• No more need to use JNDI APIs
CDAC, Mumbai11
Example // EJB 2.1// EJB 2.1
public class PayrollBean implements javax.ejb.SessionBean {
SessionContext ctx;DataSource empDB;
public void setSessionContext(SessionContext ctx) {this.ctx = ctx;}public void ejbCreate() {…Context initialContext = new InitialContext();empDB = (DataSource) initialContext.lookup (“java:comp/env/jdbc/empDB”);}
CDAC, Mumbai12
// EJB 2.1 (continued)// EJB 2.1 (continued)
public void ejbActivate() {}
public void ejbPassivate() {}
public void ejbRemove() {}
public void setBenefitsDeduction(int empId, double deduction) {
…Connection conn = empDB.getConnection();…}…}
CDAC, Mumbai13
// EJB 2.1 (continued)// EJB 2.1 (continued)
public interface PayrollHome extends javax.ejb.EJBLocalHome {
public Payroll create() throws CreateException;…}
public interface Payroll extends javax.ejb.EJBLocalObject {
public void setBenefitsDeduction (int empId, double deduction);
…}
CDAC, Mumbai14
<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>
Deployment DescriptorDeployment Descriptor
CDAC, Mumbai15
Same Example Same Example // EJB 3.0// EJB 3.0
@Statefulpublic class PayrollBean implements Payroll {@Resource DataSource empDB;public void setBenefitsDeduction (int empId, double
deduction) {Connection conn = empDB.getConnection();…}}
@Remotepublic interface Payroll {public void setBenefitsDeduction (int empId, double
deduction);}
CDAC, Mumbai16
EJB 3.0: XML Deployment DescriptorEJB 3.0: XML Deployment Descriptor
EJB3 takes a different approach to configuration– Metadata annotations are used heavily
• Especially useful for mostly static configuration: <session-type> @Stateless, <remote> @RemoteInterface
Alleviates the disconnect between Java code and XML configuration
– Defaults are used whenever possible• <transaction-type> Container, etc.
CDAC, Mumbai17
EJB 3.0: XML Deployment Descriptor contdEJB 3.0: XML Deployment Descriptor contd
Partial deployment descriptors are support– Override annotations with XML– General rule
• Use annotations when design of code is affected by metadata(i.e. @TransactionAttribute)
• Use XML when something is configurable per deployment (i.e. @RolesAllowed)
CDAC, Mumbai18
Types of BeansTypes of Beans
Session Beans
Entity Beans
Message Driven Beans
CDAC, Mumbai19
Session BeanSession Bean
Represents TaskFlow. Fills gap left by Entity Beans Describe interaction between other Beans
Types of Session Bean– Stateless Session Bean
They don’t maintain any conversational state.
– Stateful Session Bean They maintain a conversational and act on behalf of clients.
CDAC, Mumbai20
Stateless Session BeanStateless Session Bean
Does not retain any client specific data. Container has pool of instances of stateless
session beans and client requests are delegated to any available beans.
Reused by different clients. Typically implements a procedural service on top
of a database or legacy application. Ex: PayRoll that simple gets db information to
the user whose identity is given.
CDAC, Mumbai21
Stateless Session BeansStateless Session Beans
EJB 2.1: Requirements
– Home interface
– Remote/Local interface
– Bean class must implement javax.ejb.SessionBean
– XML Deployment descriptor
CDAC, Mumbai22
EJB 2.1: Required InterfacesEJB 2.1: Required Interfaces
Homes for stateless beans unnecessary Remote interface must inherit from EJBObject Remote methods must throw RemoteException
– Dependency on RMI
public interface CalculatorHome extends javax.ejb.EJBHome {
public Calculator create() throws CreateException;
}public interface Calculator extends EJBObject {
public int add(int x, int y) throws RemoteException;
public int subtract(int x, int y) throws RemoteException;
}
CDAC, Mumbai23
EJB 2.1: Bean class requirementsEJB 2.1: Bean class requirements
Must extend verbose javax.ejb.SessionBean Unnecessary and verbose callback methods
public class CalculatorBean implements javax.ejb.Sessionbean {private SessionContext ctx;public void setSessionContext(SessionContext ctx) { this.ctx = ctx; }
public void ejbCreate() { }public void ejbRemove() {}public void ejbActivate() {}public void ejbPassivate() {}
public int add(int x, int y) {return x + y;
}
public int subtract(int x, int y) {return x – y;
}
CDAC, Mumbai24
EJB 2.1: XML Deployment DescriptorEJB 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>
….
CDAC, Mumbai25
EJB 3.0 interface & classEJB 3.0 interface & class
Homeless Methods don’t throw RemoteException No verbose interface implementations
@Remote public interface Calculator {public int add(int x, int y);public int subtract(int x, int y);
}@Stateless Public class CalculatorBean implements
Calculator {public int add(int x, int y) {
return x + y; }public int subtract(int x, int y) {
Return x – y;}
}
CDAC, Mumbai26
LifeCycle of stateless session beanLifeCycle of stateless session bean
Does Not Exist
Method ready Pool
Class.newInstance();
Injections
@PostConstrauct
@PreDestroy()
Business Method
CDAC, Mumbai27
Stateful Session BeansStateful Session Beans
Maintains client-specific session information (called conversational state) across multiple method calls and transactions
Aware of client history
Each stateful session bean has a timeout value
The bean instance is destroyed and the remote reference is invalidated after the timeout period is elapsed.
CDAC, Mumbai28
Stateful Session BeansStateful Session Beans Still homeless
– Created as they are looked up @Remove replaces EJBObject.remove Stateful bean is removed after method called
@Remote public interface ShoppingCart {public void addItem(int prodId, int quantity);public void checkout();
}
@Stateful public class ShoppingCartBean implements ShoppingCart {
@Removepublic void checkout() { …}
}
CDAC, Mumbai29
EJB 3.0 Deployment DescriptorEJB 3.0 Deployment Descriptor
Believe it or not, people like XML deployment descriptors
Externalize configuration
Externalize system architecture
Although not in draft, XML DDs are optional
Replace annotations with XML and you get pure POJOs
CDAC, Mumbai30
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)
Home interface not needed in client view
Remoteness is handled transparently• No checked RemoteExceptions (unless you want them)• EJBExceptions (unchecked exceptions) are thrown instead
CDAC, Mumbai31
Example // EJB 2.1// EJB 2.1…Context initialContext = new InitialContext();
ShoppingCartHome myCartHome = (ShoppingCartHome)
initialContext.lookup(“java:comp/env/ejb/cart”);
ShoppingCart myCart = myCartHome.create();
// Use the beanCollection widgets = myCart.startToShop(“widgets”);…
// Don’t forget to handle javax.Naming.NameNotFoundException// Don’t forget to handle javax.ejb.CreateException// Don’t forget deployment descriptor (ejb-refs, etc.)}
CDAC, Mumbai32
Example: EJB 3.0 Client View
…@EJB ShoppingCart myCart;…Collection widgets = myCart.startToShop(“widgets”);
OR
Context ctx = new InitialContext();Collection c =
(Collection)ctx.lookup(Collection.class.getName() );
CDAC, Mumbai33
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 noextra code)
Stateful Session Beans• Container creates bean instance when businessmethod is invoked• Initialization is part of application semantics Don’t need a separate interface and ejbCreate methodfor it• Can use new SFSB class with “legacy” Home @Init annotation denotes bean method that plays role ofejbCreate
CDAC, Mumbai34
Dynamic Lookup
Dynamic lookup is simplified as well
EJBContext.lookup method is used at runtime
JNDI APIs are removed from developer’s view
Annotations to specify environment
dependencies are expressed on bean class • Same annotations as used for injection
CDAC, Mumbai35
ExampleExample
@Resource(name=“productDB”, type=javax.sql.DataSource)@Stateful public class ShoppingCartBeanimplements ShoppingCart {@Resource SessionContext ctx;public Collection startToShop(String productName) {…DataSource productDB =(DataSource)ctx.lookup(“productDB”);Connection conn = myDB.getConnection();…}…}
CDAC, Mumbai36
LifeCycle of a stateful session beanLifeCycle of a stateful session bean
Does Not Exist
Method Ready Passive
Class.newInstance()
Injections
@PostConstruct()
@PreDestroy()
@PrePassivate()
@PostActivate()
timeout
timeout
Instance throws exception
CDAC, Mumbai37
Entity BeansEntity Beans
POJO based persistence
CDAC, Mumbai38
Goals of Entity BeansGoals of Entity Beans
Same goals as session beans– Fewer interfaces, optional XML DDs, etc.
No required interfaces or subclassing Plain Java based
– Allow new() Provide full Object/Relational mapping Supports Inheritance Expanded EJBQL
– Fully featured– Parallel SQL– Polymorphic Queries
CDAC, Mumbai39
Defining Entity BeansDefining Entity Beans
O/R Mapping Metadata as annotations– Table mappings, @Table, @SecondaryTable– Column mappings, @Column, @JoinColumn– Relationships, @ManyToOne, @OneToOne, @OneToMany, @ManyToMany
– Multi-Table mappings, @SecondaryTable– Embedded objects, @Dependent– Inheritance, @Inheritance, @DiscriminatorColumn
– Identifier + Version properties, @Id, @Version
CDAC, Mumbai40
Entity AnnotationsEntity Annotations
@Entity@Table(name=“AUCTION_ITEM”)public class Item {
private long id; private String description; private String productName;
@Id(generate=GeneratorType.AUTO) @Column(name=“ITEM_ID”) public long getId() { return id; }
public void setId(long id) { this.id = id; }
CDAC, Mumbai41
Entity AnnotationsEntity Annotations
@Entity@Table(name=“AUCTION_ITEM”)public class Item { private long id; private String description; private String productName; private User seller;
@Id(generate=GeneratorType.AUTO) @Column(name=“ITEM_ID”) public long getId() { return id; } public void setId(long id) { this.id = id;
create table AUCTION_ITEM(ITEM_ID Number,DESC varchar(255),ProductName varchar(255),USER_ID Number);
CDAC, Mumbai42
Entity AnnotationsEntity Annotations
@Entity@Table(name=“AUCTION_ITEM”)public class Item { private long id; private String description; private String productName; private User seller;
@Id(generate=GeneratorType.AUTO) @Column(name=“ITEM_ID”) public long getId() { return id; } public void setId(long id) { this.id = id;
create table AUCTION_ITEM(ITEM_ID Number,DESC varchar(255),ProductName varchar(255),USER_ID Number);
CDAC, Mumbai43
Entity AnnotationsEntity Annotations
@Column(name=“DESC”, nullable=false, length=500) public String getDescription() { return description; } public void setDescription(String desc) { this.description = desc; } public String getProductName() { return productName; } protected void setProductName(String name) { this.productName = name; }
create table AUCTION_ITEM(ITEM_ID Number,DESC varchar(500),ProductName varchar(255),OWNER_ID Number);
CDAC, Mumbai44
RelationshipsRelationships
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.
CDAC, Mumbai45
Entity RelationshipsEntity Relationships
@OneToOne(fetch=LAZY) @Column(name=“OWNER_ID”) public Owner getOwner() { return owner; }
protected void setOwner(Owner owner) { this.owner = owner; }
@OneToMany(cascade=ALL) @JoinColumn(name=“ITEM_ID”) protected Set<Bid> getBids() { return bids; } protected void setBids(Set<Bid> bids) { this.bids = bids; }
CDAC, Mumbai46
Entity RelationshipsEntity Relationships
@OneToOne(fetch=LAZY) @Column(name=“OWNER_ID”) public Owner getOwner() { return owner; } protected void setOwner(Owner user) { this.owner = owner; } @OneToMany(cascade=ALL) @JoinColumn(name=“ITEM_ID”) protected Set<Bid> getBids() { return bids; } protected void setBids(Set<Bid> bids) { this.bids = bids; }
create table AUCTION_ITEM(ITEM_ID Number,DESC varchar(255),ProductName varchar(255),OWNER_ID Number);
create table BID (…ITEM_ID Number…);
CDAC, Mumbai47
Multi-TableMulti-Table
Multi-Table Mappings, – Entity can be stored in one or more tables
– @SecondaryTables, @SecondaryTable
CDAC, Mumbai48
Multi-table MappingsMulti-table Mappings
@Entity @Table(name=“OWNER”)@SecondaryTable(name=“ADDRESS” join={@JoinColumn(name=“ADDR_ID”)})public class Owner { private long id; private String name; private String street; private String city; private String state; @Id(generate=GeneratorType.AUTO) @Column(name=“OWNER_ID”) public long getId() { return id; } public void setId(long id) { this.id = id; }
create table OWNER(OWNER_ID Number,NAME varchar(255),);
create table ADDRESS (ADDR_ID Number,STREET varchar(255),CITY varchar(255),STATE varchar(255));
CDAC, Mumbai49
Multi-table MappingsMulti-table Mappings
… @Column(name=“STREET”, secondaryTable=“ADDRESS”) public String getStreet() { return street; } public void setStreet(String street) { this.street = street; }
@Column(name=“CITY”, secondaryTable=“ADDRESS”) public String getCity() { return city; } protected void setCity(String city) { this.city = city; }
create table OWNER(OWNER_ID Number,NAME varchar(255),);
create table ADDRESS (ADDR_ID Number,STREET varchar(255),CITY varchar(255),STATE varchar(255));
CDAC, Mumbai50
Interacting With Entity BeanInteracting With Entity Bean
Plain Java Objects
CDAC, Mumbai51
Entity ManagerEntity Manager
EntityManager is the central service for all persistence actions.
Entities are plain java objects that are allocated just like any otherJava object. They do not become persistent until your code explicitly interacts with the EntityManager to make them persistent.
The EntityManager manages the O/R mapping between a fixedset of entity classes and an underlying data source. It provides API’sfor creating queries, finding objects, synchronizing objects, andinserting objects into the database.
EntityManager also can provide caching and manage the interactionbetween an entity and transactional services in a Java EE environentsuch as JTA.
CDAC, Mumbai52
Entity ManagerEntity Manager
All entities persisted by the EntityManager service– All access through this service– Creation, retrieval, removal, and merging– Analogous to Hibernate Session
Entity manager manages persistence contexts .
The entity manager tracks all entity objects within a persistence context for changes and updates made, and flushes these changes to the database using the flush mode rules.
Once the object is detached from a persistence context, it can nolonger be managed by an entity manager, and any state changesto this object instance will not be synchronized with the database.
Injected with dependency injection
CDAC, Mumbai53
EntityManagerEntityManager
@Stateless public class ItemImpl implements ItemRemote {
@PersistenceContext(unit name=“item”)EntityManager entityManager;
public long create(Item item) { em.create(item); return item.getId(); }
public Item findById(long id) { return (Item) em.find(Item.class, id); }
public void merge(Item item) { em.merge(item); }}
CDAC, Mumbai54
Persistence ContextPersistence Context
A persistence context is a set of managed entity object instances.
There are two types of persistence contexts: 1. Transaction-scoped persistence context2. Extended persistence context
Transaction-scoped persistence context :
Persistence context may live as long as a transaction and be closedwhen a transaction completes. This is called a transaction-scoped persistence context.
When the transaction completes, the transaction-scoped persistencecontext will be destroyed and all managed entity object instanceswill become detached.
CDAC, Mumbai55
Persistence Context contd.Persistence Context contd.
Application server managed persistence contexts can be transction-scoped. In other words, only Entity Manager instances injected with the @PersistenceContext annotation or its XML equivalent maybe transaction-scoped.
@PersistenceContext(unit name=“titan”)EntityManager entityManager;
@TransactionAttribute(REQUIRED)public Customer someMethod() {Customer cust = entityManager.find(Customer.class,1);cust.setName(“new name”);return cust;}
CDAC, Mumbai56
Persistence Context contd.Persistence Context contd.
Extended Persistence Context
Persistence contexts may also be configured to live longer than atransaction. This is called an extended persistence context.
Entity object instances that are attached to an extended contextremain managed even after a transaction is complete.
This feature is extremely useful in situations where you want tohave a conversation with your database but not keep a long-running transaction, as transactions hold valuable resourceslike JDBC connections and database locks.
CDAC, Mumbai57
Persistence Context contd.Persistence Context contd.
@PersistenceContext(unitName=“titan”, type=PersistenceContextType.Extended)
private EntityManager extendedManager;….Customer cust = null;transaction.begin(); //start tranasaction 1cust = extendedManager.find(Customer.class,1);tranasction.commit(); // tranasaction 1 ends
transaction.begin(); // start transaction 2cust.setName(“bill”);extendedManager.flush();tranasaction.commit(); // cust instance remains managed and changes // are flushed
CDAC, Mumbai58
Create the objectsCreate the objects
Create the entities like you would any other object Allocate entire object graph like any other Java code
Item item = new Item();item.setDescription(“O’reilly’s EJB 4th Edition”);item.setProductName(“EJB 2.1 Book”);…Owner bill = new Owner();bill.setName(“Bill”);item.setOwner(bill);Bid bid = new Bid();…HashSet<Bid> bids = new HashSet();bids.add(bid);item.setBids(bids);
CDAC, Mumbai59
Packaging a Persistence UnitPackaging 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.
CDAC, Mumbai60
EntityManagerFactoryEntityManagerFactory
In Java SE, entity managers are created using javax.pesistence.EntityManagerFactory.
public interface EntityManagerFactory {EntityManager createEntityManager();EntityManager createEntityManager(java.util.Map map);void close();boolean isOpen();}
The createEntityManager() methods return EntityManager instances that manage a distinct extended persistence context.
CDAC, Mumbai61
Interacting with an EntityManagerInteracting with an EntityManager
The EntityManager API has methods to insert and remove entitiesfrom a database as well as merge, updates from detached enityinstances.
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
...}
CDAC, Mumbai62
InheritanceInheritance
This feature was completely absent in EJB 2.1
Persistence mapping supports inheritance– Single table per hierarchy – SINGLE_TABLE
– Join table per subclass – JOINED
– Distinct table per subclass – UNION
Queries on class hierarchy are polymorphic
CDAC, Mumbai63
Inheritance – SINGLE_TABLEInheritance – SINGLE_TABLE
@Entity@Table(name="Animal")@Inheritance(strategy=InheritanceType.
SINGLE_TABLE)@DiscriminatorColumn(name="TYPE")public class Animal { @Id private int id; @Column(name="AVG_WEIGHT") private int averageWeight;...}
@Entity@Inheritance(strategy=InheritanceType.
SINGLE_TABLE)public class Dog extends Animal{ @Column(name="BREED") private String breed;...}
create table Animal (ID Number,TYPE varchar(255),AVG_WEIGHT Number,BREED varchar(255));
CDAC, Mumbai64
Inheritance – JOINEDInheritance – JOINED
@Entity@Inheritance(strategy=InheritanceType.JOINED)@Table(name="Animal")public class Animal{ @Id private int id; @Column(name="AVG_WEIGHT") private int averageWeight;...}
@Entity@InheritanceJoinColumn(name="DOGY_ID")@Table(name="Doggy")public class Dog extends Animal{ @Column(name="BREED") private String breed;...}
create table Animal(ID Number,TYPE varchar(255),AVG_WEIGHT Number);
create table Doggy (DOGGY_ID Number,BREED varchar(255));
CDAC, Mumbai65
Inheritance – UNIONInheritance – UNION
@Entity@Inheritance(strategy=InheritanceType.TABLE_P
ER_CLASS)@Table(name="Animal")public class Animal{ @Id private int id; @Column(name="AVG_WEIGHT") private int averageWeight;...}
@Entity@InheritanceJoinColumn(name="DOGY_ID")@Table(name="Doggy")public class Dog extends Animal{ @Column(name="BREED") private String breed;...}
create table Animal(ID Number,TYPE varchar(255),AVG_WEIGHT Number);
create table Doggy (DOGGY_ID Number,BREED varchar(255));
CDAC, Mumbai66
Query APIQuery 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
@Session public class ItemImpl { … public List findByDescription(String description, int page) {
return em.createQuery(“from Item i where i.description like :d”) .setParameter(“d”, description) .setMaxResults(50) .setFirstResult(page*50) .listResults();}
CDAC, Mumbai67
EJB QL 3.0EJB QL 3.0
EJBQL 3.0 is very similar to HQL (Hibernate Query Language)
Aggregation, projection– select max(b.amount) from Bid b where b.item = :id
– select new Name(c.first, c.last) from Customer c
Fetching– from Item i left join fetch i.bids
Subselects– from Item i join i.bids bid where bid.amount = (select max(b.amount) from i.bids b)
Group By, Having, Joins
CDAC, Mumbai68
Entity Life-cycleEntity Life-cycle
CDAC, Mumbai69
Entity Callbacks & ListenersEntity Callbacks & Listeners
PrePersist PostPersist PostLoad PreUpdate PostUpdate PreRemove PostRemove
Entity Listeners are classes that can generically intercept entity callback events. You can assign methods on an entity listeners class to intercept a particular life cycle event.
CDAC, Mumbai70
Message-driven Beans
A message driven bean is an enterprise bean that allows J2EE applications to process messages asynchronously.
It acts as a JMS listener, which is similar to an event listener except that it receives messages instead of events.
The messages can be sent by any J2EE component: an application client, another enterprise bean, or a web component, or a non-J2EE system using JMS.
Retain no data or conversational state.
CDAC, Mumbai71
Message-driven Beans
Message-driven beans were already the simplest component in EJB 2.1
Message-driven beans in EJB 3.0• Bean class implements message listener interface or designates with @MessageListener
• No requirement to implement MessageDrivenBean, etc.
CDAC, Mumbai72
JMS Messaging ModelsJMS Messaging Models
Publish-and-Subscribe ( 1 -> many )
Publisher Topic
Topic
Topic
CDAC, Mumbai73
JMS Messaging ModelsJMS Messaging Models
Point-to-Point ( 1 -> 1 )
Sender Queue
Potential Reciever
Potential Reciever
CDAC, Mumbai74
Basics of JMSBasics of JMS
ConnectionFactory & Topic
Connection & Session
Message Producer
Message Consumer
Message Type
CDAC, Mumbai75
JMS Programming ModelJMS Programming Model
Connection Factory
Connection
Session
Message ConsumerMessage Consumer
Destination Destination
creates
creates
createscreates
creates
MsgSends to Sends to
CDAC, Mumbai76
Example
Just implements MessageListener
XML turns to annotations
@MessageDriven( activationConfig={@ActivationConfigProperty(
propertyName=“destinationType”, propertyValue=“javax.jms.queue”)})
public class EmailBean implements MessageListener {
void onMessage(Message msg) { }public int add(int x, int y) {
return x + y; }
}
CDAC, Mumbai77
Life CycleLife Cycle
Does Not Exist
Method-Ready Pool
Class.newInstance()
Injections
@postConstruct
@PreDestroy()
Business methods
CDAC, Mumbai78
Timer ServiceTimer Service
The Timer Service is a facility of the EJB Container system that provides a timed event API, which can be used to schedule timers for specific dates, periods and intervals.
To use Timer Service, your beans must implement the javax.ejb.TimedObject interface.
Or put @Timeout annotation on your desired method.
@TimeoutPublic void maintainence(javax.ejb.Timer timer){….. }
CDAC, Mumbai79
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
CDAC, Mumbai80
Transactions contd.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
CDAC, Mumbai81
Example
@Stateless public class PayrollBean implements Payroll {
@TransactionAttribute(REQUIRED)public void setBenefitsDeduction (int empId, doublededuction) {…}
public double getBenefitsDeduction(int empId) {…}
public double getSalary(int empId) {…}
@TransactionAttribute(REQUIREDNEW)public void setSalary(int empId, double salary) {…}…}
CDAC, Mumbai82
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 businessmethod 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
CDAC, Mumbai83
Example
// Security view@Stateless public class PayrollBean implements Payroll {public void setBenefitsDeduction (int empId, doublededuction) {…}
public double getBenefitsDeduction(int empId) {…}
public double getSalary(int empId) {…}// salary setting is intended to be more restricted
@RolesAllowed(“HR_PayrollAdministrator”)public void setSalary(int empId, double salary) {…}…}
CDAC, Mumbai84
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 separateinterceptor class or on bean class
PostConstruct and PreDestroy annotationsadopted into JSR-250 (“Common Annotations”)
CDAC, Mumbai85
Example
@Stateful public class AccountManagementBeanimplements AccountManagement {Socket cs;@PostConstruct@PostActivateprivate void initRemoteConnectionToAccountSystem () {…}@PreDestroy@PrePassivateprivate void closeRemoteConnectionToAccountSystem () {…}}
CDAC, Mumbai86
Interceptors
Powerful facility for more advanced developers.
Interception of invocations of business methods, message listener methods.
Invocation model: “around” methods• Wrapped around business method invocations• Interceptor has control over invocation of “next
method”• Can manipulate arguments and results• Context data can be carried across interceptor invocation chain• Can use deployment descriptor to override order or to add interceptors
CDAC, Mumbai87
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 hierarchyget invoked for a given class or method• Ability to exclude default interceptors and/or classlevelinterceptors
CDAC, Mumbai88
Example
@Interceptors({in.cdac.AccountAudit.class,in.cdac.Metrics.class,in.cdac.CustomSecurity.class})@Stateless public class AccountManagementBeanimplements AccountManagement {…public void createAccount (int accountId, Details details) {…}public void deleteAccount (int accountId) {…}public void activateAccount (int accountId) {…}public void deactivateAccount (int accountId) {…}…}
CDAC, Mumbai89
Example
public class AccountAudit{@AroundInvokepublic Object auditAccount (InvocationContext inv)throws Exception{try {Object result = inv.proceed();
return result;} catch (Exception ex) {throw ex;}……}}
CDAC, Mumbai90
SummarySummary 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 existingapplications
Gives developer simple-to-use and powerfulcapability
CDAC, Mumbai91
QuestionsQuestions