oracle container 4 java 10.1.3.1 paolo ramasso · oracle & jpa 1.0 • ejb 3.0 and jpa 1.0...
TRANSCRIPT
Paolo RamassoPrincipal Sales ConsultantOracle Fusion Middleware
Enterprise Java Beans Oracle Container 4 Java 10.1.3.1
(OC4J)
Oracle Fusion Middleware
Quick Intro...EJBs ???!!
• A Programming Model for Server Side Reusable Components
• Encapsulation of Business Logic• Allows Components to be Distributable Objects• Typical usage...Model in MVC
Why EJBs ???!!
• EJBs enable faster application development.• EJBs encapsulate business logic that can be
invoked by remote clients.• EJBs exist in the middle tier that provides
standard and robust architecture.• EJBs allow reuse of business components.• EJBs live in containers providing services such as
support for transactions, persistence, and access control for the beans.
EJB Architecture
EJB client
EJB server
Enterprise ServicesNaming Service, Transaction
Service, SecurityDeployment descriptor
Database
EJB container
EJB bean
EJB remote object
EJB home object
EJB remote
interface
EJB home
interface
“legacy EJB” EJB 2.x• 4 to 6 parts• Home/LocalHome Interface• the ‘lifecycle’ interface of the EJB• Defines the methods with which you create, retrieve
and destroy EJBs• consists of create method, finder methods (Entity
beans) and destroy methods• Remote/Local Interface• the ‘business’ Interface of the EJB• Defines which methods are exposed to a client
• Bean Class• the implementation of the EJB business methods
Types of EJBs
• Session Beans - Stateful- Stateless
• Entity Beans - Container Managed Persistence- Bean Managed Persistence (forget them!!!)
• MessageDriven Beans - Listen to JMS endpoints (queues/topics)
Types of EJBsSession Beans
• Stateless beans:Hold conversations that span a single method call (implement your business meths here)• Stateful beans:
Hold conversations with clients that may span many method calls(implement your business meths here)
Types of EJBsEntity Beans
• Business entities that are used to represent data in the database• Sharable across multiple clients• Are persistent: • Container managed persistent (CMP) beans - data
is persisted by the container so no SQL in the bean• Bean managed persistent (BMP) beans - data
maintained by the bean itself, so SQL in the bean
Container Managed Transactions
• Declarative Transaction Management• Specify Transaction Attributes in EJB Deployment
Descriptor• No Transactional logic in Business Logic
• Set Transaction Attributes for all methodsor individual methods in an EJB
• Mandatory • Required• RequiresNew• Supports• ...
Deployment Descriptor
• Deployment descriptor:• Specified in J2EE• Specifies run-time attributes of the bean for
deployment• Allows customization of the run-time behavior of
enterprise beans• EJB-jar files:
A standard format used by EJB deployment tools for packaging enterprise beans with their declarative information
Let’s move to EJB 3.0…
• Simplify Development• EJB = Plain Java Object (POJO)• Use metadata annotations• Reduce number of artifacts• Attract broad range of developers
• Standardize persistence API• O-R Mapping similar to Oracle TopLink,
Hibernate• EntityManager API for CRUD Operations
EJB 3.0 Simplification
• POJO and POJI• Removes complexity of earlier versions using
simple and familiar Java artifacts• EJB Class will be a POJO• EJB Interface will be a POJI (no EJB extensions)• No need for home interface• Annotations for type of EJB and interface
Oracle & EJB 3.0 Support
• OracleAS 10.1.3.0• Container was close to final draft
• OracleAS 10.1.3.1• Complete EJB 3.0 Support in the Container
• Aligns with Final Spec• Oracle extensions
• JPA Based on TopLink Essentials• Annotations support in Web and Application client
Container
Oracle & JPA 1.0
• EJB 3.0 and JPA 1.0 finalized at JavaOne 2006• Oracle keynote and demonstration grounds
• Project Glassfish reference implementation of JPA • Provided by TopLink Essentials
• OracleAS 10.1.3.1 EJB 3.0/JPA 1.0 updates• EJB 3.0 final version• JPA 1.0 – default to TopLink Essentials• Oracle JDeveloper – updates to match runtime• Eclipse Dali – M3 release at JavaOne
Configuration by Exception
• Minimize configuration• Use generally accepted defaults• Only configure that what is different from the
defaults
Working with Dependency Injection
Dependency injection:• Eliminates use of JNDI complexities• Results in less lines of code• Yields more concise code• Can be overridden with XML elements in deployment
descriptors• Can't be used with helper classes, which must use
JNDI services
EJB 3.0 Annotations
Metadata annotations & deployment descriptor:• Deployment properties • Persistence
Annotations are optional (J2SE 1.5 is required) deployment descriptors can also be used, ala EJB 2.1
Examples:@Resource, @EJB etc…
The @EJB The @Resource
Session Beans and Interfaces package ejb30test;import javax.ejb.Remote;@Remotepublic interface EJBInjecter {
public String facadeMeth(String s);}
package ejb30test;
import javax.ejb.Local;@Localpublic interface EJBInjecterLocal {}
Session Beans and Injection
@Stateless(name="EJBInjecter")public class EJBInjecterBean implements EJBInjecter,
EJBInjecterLocal {
@EJB(beanName="EJBToBeInjected", beanInterface=EJBToBeInjected.class)EJBToBeInjected ejbinjected;
@EJB(beanName="EJBToBeInjected", beanInterface=EJBToBeInjectedLocal.class)EJBToBeInjectedLocal ejbinjectedlocal;
Session Beans and Injection@Stateful(name="WhatDriverEJB")public class WhatDriverEJBBean implements
WhatDriverEJB, WhatDriverEJBLocal {@Resource(name="jdbc/OracleDS") public DataSource mylocalscott;
…try
{System.out.println("getting a new
connection from the pool");conn= mylocalscott.getConnection();
}
Stateful Session Beans and Callback Interceptor Methods
@StatefulDeployment(idletime=10,timeout=15)@Stateful(name="WhatDriverEJB")public class WhatDriverEJBBean implements WhatDriverEJB,
WhatDriverEJBLocal {…@PostConstruct
public void itIsAnInit() {System.out.println("PostConstruct
WhatDriverEJBBean.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() {
…@PostActivate
public void goActivate() {…@Remove
public void iMDone() {System.out.println("WhatDriverEJBBean.iMDone");}
EJB Client Samplepublic class WhatDriverEJBClient2 {
public static void main(String [] args) {try {
final Context context = getInitialContext();WhatDriverEJB whatDriverEJB =
(WhatDriverEJB)context.lookup("WhatDriverEJB");// Call any of the Remote methods below to access the EJB
whatDriverEJB.justKick( );// whatDriverEJB.iMDone( ); to force remove
} catch (Exception ex) {ex.printStackTrace();
}}private static Context getInitialContext() throws
NamingException {…
Interceptors
EJB 3.0 introduces the ability to create custom interceptor methods and classes that are called before invoking the methods they intercept.
Interceptors are:• available for session beans (stateless and stateful) and
message-driven beans• Provide more granular control of a bean's method invocation
flow• Useful to implement custom transaction, security,
logging…AOP
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();
}
Interceptorspublic class LogMyTest {
@Resourceprotected SessionContext sessionCtx;
public LogMyTest() {System.out.println("LogMyTest.LogMyTest");
}@AroundInvokepublic Object iGotIt(InvocationContext ctx) throws
Exception {
System.out.println("iGotIt: I GOT YOUR CALL AND YOU ARE LOGGED AS "+sessionCtx.getCallerPrincipal());
return ctx.proceed();}
@WebService
package jmssenderws;import javax.ejb.Local;
import javax.jws.WebService;
@WebServicepublic interface SessionEJBJMSWSLocal {
public String pushIt(String s);}
EJB 3.0 WS: you may choose to annotate an interface or the bean class using @WebService annotation or use @WebMethod to annotate class methods to be exposed as WS operation.
@WebService
@Stateless(name="SessionEJBJMSWS")public class SessionEJBJMSWSBean implements
SessionEJBJMSWSLocal {…
public String pushIt(String s) {System.out.println("SessionEJBJMSSenderBean.pushIt");
MessageProducer producer = null;Connection connection = null;try {
Message Driven Beans 3.0…@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.0 and JAASEJB security roles:• Provide role-based access control of EJBs and their
methods• Are implemented through security annotations• – @DeclareRoles• – @RolesAllowed• – @PermitAll• – @DenyAll• – @RunAs
EJB 3.0 and JAAS@Stateless(name="SecureEJB")public class SecureEJBBean implements SecureEJB,
SecureEJBLocal {@Resource SessionContext ctx;
…@RolesAllowed("admrole")public void adm() {
System.out.println("name"+ctx.getCallerPrincipal().getName());
System.out.println("adminrole"+ctx.isCallerInRole("admrole"));
System.out.println("userrole"+ctx.isCallerInRole("usrrole"));
…
“Mr. Persistence Manager”Toplink Essentials
• Move to lightweight POJO solutions• Has always been supported by TopLink• Used by majority of our customer base
• Standardization of ORM support in Java EE• EJB 3.0 (JSR 220)
• Need and benefits of ORM solutions are better recognized
EJB 3.0 Persistence• Lightweight POJO entity model
• Portable (Serialization – detachment), • Container transaction and security config
simplified• Modularized EntityManager API • Usable outside container (Java SE)
• Standardized O/R mappings • Specified using annotations and/or XML• Supporting multiple tables, etc.
• Dynamic queries, named queries and SQL queries
Application
RDBMS
EntityManager
MyEntity Application
Components
Persistence.xml
ORM XML
MyEntityMyEntityMyEntity
find(…)create*Query(…)persist(…)remove(…)merge(…)refresh(…)contains(…)flush()
EntityManagerFactory
EJB 3.0 Persistence EJB Development
• EJB 3.0 Development• Simplified EJB development
• JPA support• Including Testing outside the
container• Dialog based EJB creation• Reverse engineering DB into
Entity Beans• Session Façade Generation• One-click sample client creation
for testing
An Entity…import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.Id;import javax.persistence.NamedQuery;import javax.persistence.Table;@Entity@NamedQuery(name="findAllDog", query="select
object(o) from Dog o")@Table(name="DOG")public class Dog implements Serializable {
private Long age;private Long dogid;private String name;
public Dog() {}
An Entity…public Long getAge() {
return age;}public void setAge(Long age) {
this.age = age;}@Id@Column(nullable=false)public Long getDogid() {
return dogid;}public void setDogid(Long dogid) {
this.dogid = dogid;}
…
Some Mapping Annotations• Direct
• @Basic• @Lob…
• Relationship• @OneToOne• @ManyToOne• @ManyToMany• …
• @Transient – attribute not persistent
Mappings Examples@Entity@NamedQuery(name="findAllDog", query="select
object(o) from Dog o")@Table(name="DOG")public class Dog implements Serializable {…private List<Rate> rateList;…@OneToMany(fetch =FetchType.Lazy, mappedBy="dog")
public List<Rate> getRateList() {return rateList;
}public void setRateList(List<Rate> rateList) {
this.rateList = rateList;}
More Mapping Examplespublic class Distintaanticipo implements Serializable {
@SequenceGenerator(name="D_SEQ", sequenceName="DISTINTAANTICIPO_SEQ")@Id @GeneratedValue(generator="D_SEQ")@Column(name="K_DISTINTA", nullable = false)private Long kDistinta;private String operator;private Timestamp submission;@OneToMany(mappedBy = "distintaanticipo"
,cascade=CascadeType.PERSIST)private List<Distintaappuntoant> distintaappuntoantList;@OneToOne(cascade=CascadeType.PERSIST)@JoinColumn(name="K_RIF_INTERNO_DOC",
referencedColumnName = "K_RIF_INTERNO_DOC")private Appuntodocumento appuntodocumento;
Other Annotations
• Optimistic Locking• @Version
• Inheritance• @Inheritance• Strategy = InheritanceType
• InheritanceType• SINGLE_TABLE• TABLE_PER_CLASS• JOINED
Inheritance Example• @Entity
@Table(name="EJB_PROJECT")@Inheritance(strategy=JOINED, discriminatorValue="P")@DiscriminatorColumn(name="PROJ_TYPE")public class Project implements Serializable{...}@Entity@Table(name="EJB_LPROJECT")@Inheritance(discriminatorValue="L")public class LargeProject extends Project {...}@Entity@Table(name="EJB_PROJECT")@Inheritance(discriminatorValue="S")public class SmallProject extends Project {...}
EntityManager API• Querying
• Retrieval of Entities from database• Transactions
• Applying Changes to Entities• General
• isOpen()• close()• contains(Object entity)
• Persistence API Usage• Container Managed• Application Managed
Entity Manager Injection@Stateless(name="FacadeEJB")public class FacadeEJBBean implements
FacadeEJB, FacadeEJBLocal {@PersistenceContext(unitName="ejb30persist")
private EntityManager em;
public FacadeEJBBean() {}
public Object mergeEntity(Object entity) {return em.merge(entity);
}…
Writing Basic JPQL StatementsSELECT object(o)FROM abstract-schema-name o[WHERE condition]
Examples:SELECT object(o) FROM Users o
SELECT object(o) FROM Users oWHERE o.email = '[email protected]'
SELECT object(o) FROM Users oWHERE o.firstName = :givenName
Querying API
• find(Class/String entityType, Object primaryKey)• refresh()• createQuery(String ejbql)• createNamedQuery(String queryName)• createNativeQuery(String sql, Class/String
entityType)
EntityManager Find
• Employee employee = (Employee)em.find("Employee", id);
• Employee employee = em.find(Employee.class, id);
Named Query Example
@Entity@NamedQueries({@NamedQuery(name="findADogbyname",
query="select object(o) from Dog o where o.name=:am"),@NamedQuery(name="findAllDog", query="select object(o) from Dog o")})
@Table(name="DOG")public class Dog implements Serializable {…
Named Query Example…@Stateless(name="SessionEJB")public class SessionEJBBean implements SessionEJB,
SessionEJBLocal {
…/** <code>select object(o) from Dog o where o.name=:am</code> */public Dogs findADogbyname(Object am) {return
em.createNamedQuery("findADogbyname").setParameter("am", am).getResultList(); }
…
Transaction API
• merge(Object entity)• persist(Object entity)• remove(Object entity)• Etc…
Persisting New Entities
import javax.persistence.EntityManager;
@Stateless(name="SessionEJB")public class SessionEJBBean implements
SessionEJB, SessionEJBLocal {
@PersistenceContext(unitName="ejb30persist")private EntityManager em;
public Object persistEntity(Object entity) {em.persist(entity);return entity;
}
Merging Detached Entities
import javax.persistence.EntityManager;
@Stateless(name="SessionEJB")public class SessionEJBBean implements
SessionEJB, SessionEJBLocal {
@PersistenceContext(unitName="ejb30persist")private EntityManager em;
public Object mergeEntity(Object entity) {return em.merge(entity);
}
Removing Entities
import javax.persistence.EntityManager;
@Stateless(name="SessionEJB")public class SessionEJBBean implements
SessionEJB, SessionEJBLocal {
@PersistenceContext(unitName="ejb30persist")private EntityManager em;
public void removeEntity(Object entity) {em.remove(em.merge(entity));
}
Refreshing Entities
import javax.persistence.EntityManager;
@Stateless(name="SessionEJB")public class SessionEJBBean implements
SessionEJB, SessionEJBLocal {
@PersistenceContext(unitName="ejb30persist")private EntityManager em;
public Object refreshEntity(Object entity) {em.refresh(entity);return entity;
}
EJB Transaction ModelDemarcating a transaction determines:
• Who begins and ends a transaction• When each of these steps occur• A container-managed (declarative) transaction (CMT):– Is demarcated by the container– Is specified implicitly (by default) or declarativelythrough the use of annotations
• A bean-managed (explicit) transaction (BMT):– Is demarcated by the bean– Is specified programmatically in the bean through JTAinterface or Java Database Connectivity (JDBC) interface
Container-Managed Transactions
@TransactionManagement(CONTAINER)• Container-Managed Transactions can specify one ofthe following @TransactionAttribute annotations:– REQUIRED (default)– SUPPORTS– MANDATORY– NEVER– REQUIRES_NEW– NOT_SUPPORTED• The transaction attribute can be specified at:– Class Level: Applies to all Business Methods– Method Level: Applies to Method
Container-Managed Transactions
CMT - setRollbackOnly() – getRollbackOnly()
• The setRollbackOnly() method controlstransaction state in the bean for a CMT.
• The setRollbackOnly() method can mark currenttransaction for rollback.
• If a transaction is marked for rollback, then container rolls back the transaction before returning to the caller.
Bulk UPDATE and DELETE in EJB QL
Perform batch update operations by using the Query API executeUpdate() method:
• EJB QL UPDATE example: To modify the first name and email address of a specified user
Query query = em.createQuery( "UPDATE Users u " + " SET u.firstName = 'Stephen'," + " u.email = '[email protected]'" +
" WHERE u.userId > 10");
int rowCount = query.executeUpdate();
Bulk UPDATE and DELETE in EJB QL
Perform batch delete operations by using the Query API executeUpdate() method:
EJB QL DELETE example: to delete the notifications rows for a specific user
Query query = em.createQuery("DELETE FROM Notifications WHERE n.userId > '10'");int rowCount = query.executeUpdate();
Support for Existing Applications
• A client written to the EJB 3.0 API may be a client of a component written to the EJB 2.1 or earlier API. Such clients may access components written to the EJB 3.0 APIs and components written to the earlier EJB APIs within the same transaction.
• EJB clients may access EJB 3.0 entities and/or theEntityManager together with EJB 2.x entity beans within the same transaction as well as within separate transactions.
Support for Existing Applications
• Existing EJB 2.1 and earlier applications must be supported to run unchanged in EJB 3.0 containers.
• All EJB 3.0 implementations must support EJB 1.1, EJB 2.0, and EJB 2.1 deployment descriptors for applications written to earlier versions of the Enterprise JavaBeans specification.
• An enterprise bean that is written to the EJB 2.1 or earlier API release may be a client of components written to EJB 3.0 API using the earlier EJB APIs when deployed in an EJB 3.0 container.
Oracle EJB 3.0 Extensions… Oracle EJB 3.0 Extensions…
• Vendor specific deployment annotations• Match with commonly used attributes in
• Simplification of using JPA• Ability to inject EntityManager using @Resource• persistence.xml is option in ejb-jars• Package a persistence.xml in WEB-INF/ instead of
WEB-INF/classes/META-INF
@StatelessDeployment(minInstances = 100, maxInstances = 500, poolCacheTimeout = 120)@Statelesspublic class HelloWorldBean implements HelloWorld
Oracle EJB 3.0 Extensions… Some Help
Pro EJB 3Java Persistence API■ ■ ■
Mike KeithMerrick SchincariolPro EJB 3: Java Persistence APICopyright © 2006 by Mike Keith and Merrick Schincariol
Summary• EJB 3.0 containers provide new feats like injection etc…to boost
programming easiness• EJB 3.0 fully leverages annotations• EJB 3.0 and WS development simpler than before• EJB 3.0 provides a standardized API and metadata format for
accessing ORM functionality• TODAY OracleAS 10.1.3.1 provides an EJB 3.0 implementation
based on Toplink• TopLink Essentials (EJB 3.0 RI)• You can have different EJBs version working together
Thanks for Your time