Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Beginning EJB 3Application Development
Raghu R KodaliConsulting Product Manager, & Evangelist
Oracle Fusion MiddlewareOracle USA
Author – Beginning EJB 3 Application Development (Apress)
Agenda
• An Introduction to EJB• Java Persistence API (JPA)• Session beans and Interceptors• Message-Driven Beans• Web Services• Performance
The case for EJB: A brief history
• Around 1996, EJB was conceived to unify enterprise technologies such as RMI and JTA into a standard server-side component framework
• Its mission: To define, deploy, and execute business components in a distributed, multi-user, secure environment
The case for EJB: A brief history
• As EJB evolved, it added new features and jettisoned others
• EJB 3 provides a far simplified model over its precursors
• Incorporates ideas and technology unabashedly from TopLink, Hibernate, Spring, and JDO
• Leverages JDK 1.5 features (annotations, generics)• Meta data can be specified with annotations
• XML is optional
The case for EJB: A brief history
• JSR 220: Enterprise JavaBeansTM 3.0• Java Persistence API (JPA Entities)• EJB Core Contracts and Requirements (Session Beans and MDBs)• EJB 3.0 Simplified API
EJB 3 Goals
• Simplify Development• EJB = Plain Java Object (POJO)• Use metadata annotations• Reduce number of artifacts• Attract broad range of developers• Container injection
• Standardize persistence API• O-R Mapping similar to Oracle TopLink, Hibernate• Utilize metadata annotations• EntityManager API for CRUD Operations
Configuration by Exception
• Minimize configuration• Use generally accepted defaults• Only configure that what is different from the defaults• Results in less code
• Caveat: much behavior is not evident just by looking at the code!
Agenda
• An Introduction to EJB• Java Persistence API (JPA)• Session beans and Interceptors• Message-Driven Beans• Web Services• Performance
Java Persistence API (JPA) Goals
• Simplify programming model • Lightweight POJO’s• Remove unnecessary artifacts
• Improve modelling capabilities• Inheritance and polymorphism• O/R mapping
• Extend query capabilities and language
Along The Way
• Persistence API expanded • Evolved into Java Persistence API (JPA) usable both inside and
outside Java EE Containers• Merger of expertise from Hibernate, TopLink, JDO, EJB vendors and
individuals• Pluggability
• Notion of a Persistence Provider invoked by the Container• Can mix EJB Containers and third-party Persistence Providers
POJO Entities
• Concrete classes (no longer abstract)• No required interfaces
• No required business interfaces• No required callback/life cycle interfaces
• Use new() to create instances• Direct field access or getter/setter methods
• Can contain logic (e.g. for validation, etc.)• Use Collection interfaces for relationships• Can be local or moved around
• Can be moved to any tier
Example: JPA Entity
@Entity public class Customer { private Long id;private String name;private HashSet orders = new HashSet();
@Id (generate=SEQUENCE, generator="SEQ_GEN")@SequenceGenerator(name="SEQ_GEN",
sequenceName="CUST_SEQ",allocationSize=1)
@Column(name = "ID", primaryKey = true)public Long getId() {return id;}
protected void setId (Long id) {this.id = id;}...
}
Object/Relational Mapping
• Specified as annotations or XML• Logical and physical mapping views
• Logical—object model (e.g. @OneToMany)• Physical—DB tables and columns (e.g. @Table)
• Support for basic, serialized objects and LOBs• Unary, n-ary relationship mappings• Rules for defaulting of DB table
and column names• Access to object state using fields or properties• Multiple tables, composite relationship keys
Mapping Annotations
• Direct • @Basic• @Lob• @EmbeddedId
• Relationship• @OneToOne• @ManyToOne• @ManyToMany• @JoinColumn• @JoinTable• @Embedded
• @Transient – attribute not persistent
O-R Mapping
• Sensible default mapping strategies• Use annotations to overwrite defaults
• Collection interfaces used for relationships• @OneToOne, @OneToMany, @ManyToOne,
etc.• Ability to map one or more persistent object to a
table• Embeddable
• Support for typical inheritance strategies• Single table per class hierarchy, per class, etc.
Mapping XML
• Mapping meta data may also be declared in XML, in the orm.xml file
• Meta data may be defined in both places, even for the same element
• When conflicting meta data is detected, the XML always overrides
• Allows late-bound mapping changes, for instance, without affecting the entity class itself
• The <xml-mapping-metadata-complete> tag allows assembler to declare that all mapping is contained in the orm.xml file – a deploy-time optimization
EntityManager
• An EntityManager is tied to a <persistence-unit>• Create new POJOs using their constructors (new)• EntityManager serves as untyped “home”
• Query and manipulate persistent state of entities• Injected into clients using @PersistenceContext
annotation• Provides lifecycle operations
• persist()• remove()• merge()
• Factory for Query objects
Operations on Entities
• EntityManager API—To control lifecycle of entities and create queries• persist()- Insert the identity of an entity into the db• remove()- Delete the persistent identity of the entity from the db• refresh()- Reload the entity state from the db• merge()- Synchronize the state of detached entity with the pc• find()- Execute a simple PK query• createQuery()- Create query instance using dynamic JPA QL• createNamedQuery()- Create query instance for a predefined
query• createNativeQuery()-Create query instance for an SQL query• contains()- Determine if entity is managed by pc• flush()- Force synchronization of pc to database
EntityManager API example
@PersistenceContext public EntityManager em;...public void addLoan(String provider, long term,
String loan_type, double interest_rate)
{Loans loan = new Loans();loan.setProvider(provider);loan.setTerm(term);loan.setLoanType(loan_type);loan.setInterestRate(interest_rate);em.persist(loan);
}
• Utilize JPQL (Java Persistence Query Language), Expressions, SQL• SQL allows for direct SQL over database schema
• Successor to EJBQL• Defined dynamically or stored within an Entity
public List findByName (String name) {return em.createQuery ("SELECT c FROM Customer c").getResultList();
}
JPQL: Query API
Named Queries
@NamedQuery(name=“Employee.findAll", query="select o from Employee o where
o.name = :name")
• Define parameterized queries• Replaces finder methods in EJB 2.x• Executed by EntityManager to return collection or
single-value result• Dynamic (runtime) queries also supported
META-INF/persistence.xml
• The presence of a META-INF/persistence.xml file in a .jar is required for the entities in that .jar file to be recognized
• A persistence.xml file defines one or more <persistence-unit> elements
• A <persistence-unit> in a persistence.xml file may explicitly specify the entities that it includes/excludes in the .jar
• If no entities explicitly included/excluded, all entities found in the .jar are part of the <persistence-unit>
Example persistence.xml file
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/persistence persistence_1_0.xsd" version="1.0"><persistence-unit name="default"
transaction-type="RESOURCE_LOCAL"><provider>
oracle.toplink.essentials.PersistenceProvider</provider><class>inventory.model.Inventory</class><class>inventory.model.Order</class><class>inventory.model.Item</class><properties><!–- platform-specific properties go here -->
</properties></persistence-unit>
</persistence>
JPA Deployment
• JPA persistence unit is defined by the presence of a META-INF/persistence.xml file
• When deployed, a group of colocated JPA entities, together with supporting @MappedSuperclass and other classes, is known as a persistence unit
• A persistence unit may be deployed as:• Standalone .jar file• Bundled with an EJB .jar file• Bundled with a WAR (web archive) file
Java SE vs. Java EE
• Entities can run inside or outside a Java EE container
• Java SE clients obtain an application managed EntityManager from an EntityManagerFactory
• Java SE clients can get entities through a Session bean in Java EE container, manipulate entities on client, and merge the changes
Agenda
• An Introduction to EJB• Java Persistence API (JPA)• Session beans and Interceptors• Message-Driven Beans• Web Services• Performance
EJB 3 Session bean
public interface Calculator {int add (int a, int b) int subtract (int a, int b)
}
@Statelesspublic class CalculatorBean implements Calculator {
public int add (int a, int b) {return a + b;}public int subtract (int a, int b) {return a – b;}
}
Dependency Injection
• Eliminates use of JNDI complexities• Results in fewer lines of code• Yields more concise code• Can be overridden with XML elements in deployment
descriptors
Session Beans and Injection
@Stateful(name="WhatDriverEJB")public class WhatDriverEJBBean implements WhatDriverEJB,
WhatDriverEJBLocal {
@Resource(name="jdbc/OracleDS") public DataSource mylocalscott;…public void foo() {
try {System.out.println("getting a new connection from
the pool");conn= mylocalscott.getConnection();
}…
Interceptors
• Methods and classes that are called before invoking the methods they intercept
• Only available for session beans (stateless and stateful) and MessageDriven beans
• Provide more granular control of bean method invocation flow
• Useful to implement custom transaction and security
• AOP model: aggregates behavior without interfering with the method being aggregated
• Like @EntityListener classes, a single interceptor class can serve multiple session beans or MDBs
Interceptors
@Stateless(name="BasicEJB")@Interceptors({LogMyTest.class, GenericInfo.class})public class BasicEJBBean implements BasicEJB, BasicEJBLocal
{public BasicEJBBean() {
System.out.println("BasicEJBBean.BasicEJBBean");}
… @AroundInvokepublic Object thatSIt(InvocationContext ctx) throws
Exception {System.out.println("BasicEJBBean.thatSIt I HOPE YOU
LIKE MY INTERCEPTOR DEMO");return ctx.proceed();
}
Stateful Session Beans and Callback Interceptor Methods
@Stateful(name="WhatDriverEJB")public class WhatDriverEJBBean implements WhatDriverEJB,
WhatDriverEJBLocal{…@PostConstructpublic void itIsAnInit() {System.out.println("PostConstruct WDEB.itIsAnInit");try {System.out.println("getting a new connection from the
pool");conn = mylocalscott.getConnection();
}…
Stateful Session Bean and Callback Interceptor Methods
@PrePassivatepublic void goPassivate() {… @PostActivatepublic void goActivate() {…@Removepublic void iMDone() {
System.out.println("WhatDriverEJBBean.iMDone");}
EJB 3 Deployment
• EJB 3 modules no longer require ejb-jar.xml file• Presence of 1 or more classes annotated @Stateless,
@Stateful, or @MessageDriven is sufficient for the Java EE server to recognize an EJB module
• EJB module packaged into a .jar file• May bundle a JPA persistence unit inside the EJB .jar
file, or reference it as a deployed library
EJB deployment descriptor
• Meta data may also be declared in XML, in the ejb-jar.xml file
• Meta data may be defined in both places, even for the same element
• When conflicting meta data is detected, the XML always overrides
• Allows late-bound mapping changes, for instance, without affecting the entity class itself
• The <metadata-complete> tag allows assembler to declare that all mapping is contained in the ejb-jar.xml file – a deploy-time optimization
Example ejb-jar.xml
<?xml version="1.0" encoding="windows-1252" ?><ejb-jar xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
xmlns="http://java.sun.com/xml/ns/javaee" version="3.0"><enterprise-beans><session id="SessionEJB">
<ejb-name>SessionEJB</ejb-name><mapped-name>ejb/SessionEJB</mapped-name><ejb-class>org.acme.ejb.SessionEJB</ejb-class><session-type>Stateless</session-type><transaction-type>Container</transaction-type>
</session></enterprise-beans><assembly-descriptor/>
</ejb-jar>
Agenda
• An Introduction to EJB• Java Persistence API (JPA)• Session beans and Interceptors• Message-Driven Beans• Web Services• Performance
What is a Message-Driven Bean?
• Asynchronous message consumer• Processes messages delivered via JMS• Operates on either:
• JMS queue (point-to-point model)• JMS topic (publish-subscribe model)
• Leverages enterprise services in the EJB container (security, transactions, resources, concurrency, etc.)
MessageDriven Beans
…@MessageDriven(activationConfig =
{@ActivationConfigProperty(propertyName="connectionFactoryJndiName",propertyValue="jms/QueueConnectionFactory"),@ActivationConfigProperty(propertyName="destinationName", propertyValue="jms/demoQueue"),@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue")})
public class MessageDrivenEJB30Bean implements MessageListener{public void onMessage(Message message) {
… }
EJB 3 as Web Service
• Annotate business interface• Deploys to Java EE container(s) as a Web Service• Session bean class may also identify its @WebService
endpoing interface
EJB 3 as Web Service
package buslogic;
import java.rmi.RemoteException;import java.rmi.Remote;import javax.jws.WebMethod;import javax.jws.WebService;
@WebServicepublic interface CustomerFacade{
@WebMethodpublic Integer getCreditRating(String ssn);
}
Agenda
• An Introduction to EJB• Java Persistence API (JPA)• Session beans and Interceptors• Message-Driven Beans• Web Services• Ease-of-Development & Performance
Compare # of Lines of Code
0100200300400500600700800900
1000
# of lines (Java) # of lines (XML)
EJB 2.1EJB 3.0
Conclusion(s)
• Big thumbs up on ease of use • POJO architecture is the right way to go, as it has
been proven by frameworks like TopLink, Hibernate etc…
• EntityManager API big plus• Ease of use to develop CRUD operations• Query with @NamedQuery/@NamedQueries annotations
• Testability outside container is big plus
Data Transfer Object - Results
Aggregate Average Response TimeData Transfer Object
0
500
1000
1500
2000
2500
15 U
sers
25 U
sers
50 U
sers
100 U
sers
150 U
sers
200 U
sers
250 U
sers
Mill
isec
onds
EJB 2.1 - DTO OnEJB 2.1 - DTO OffEJB 3.0
Data Transfer Object - Results
Total Transactional RateData Transfer Object
0
50
100
150
200
250
300
15 U
sers
25 U
sers
50 U
sers
100 U
sers
150 U
sers
200 U
sers
250 U
sers
Req
uest
s pe
r Sec
ond
EJB 2.1 - DTO OnEJB 2.1 - DTO OffEJB 3.0
Data Transfer Object - Conclusions
• The average difference between EJB 2.1 DTO On and EJB 3 is within the margin of error (4%)• EJB 3 behaves better under higher load
• DTO Off is about 25% less performant because every invoke to an accessor is a transaction by itself
Session Façade - Results
Aggregate Average Response TimeSession Facade
0200400600800
10001200140016001800
15 Users 25 Users 50 Users 75 Users 100Users
Mill
isec
onds
EJB 2.1EJB 3.0
Session Façade - Results
Total Transactional RateSession Facade
020406080
100120140160180
15 Users 25 Users 50 Users 75 Users 100Users
Req
uest
s pe
r Sec
ond
EJB 2.1EJB 3.0
Session Façade - Conclusions
• The difference is roughly double on both, response time and throughput• The difference increases under higher load
• EJB 2.1 System throughput is pretty much at peak for all user loads• EJB 3 shows a more typical throughput curve