Professional Documents
Culture Documents
Michael.Stal@siemens.com
Software &
Engineering 1 © Siemens AG, CT SE 2, Michael Stal
Architecture
Content
TECHNOLOGY
1. Goals
2. Session Beans
3. Message-Driven Beans
4. Entities/Persistence
4. Summary
5. Backup Material
1. Dependency Injection
2. EJB 2.1 Entitry Bean Example
Software &
Engineering 2 © Siemens AG, CT SE 2, Michael Stal
Architecture
1
TECHNOLOGY Component/Container Approach
Component Container
Software &
Engineering 3 © Siemens AG, CT SE 2, Michael Stal
Architecture
Deployment Contract
TECHNOLOGY
External Interface
Factory Interface
Implementation Metainfo
Resources
Meta Information
Deployment
CONTAINER
Software &
Engineering 4 © Siemens AG, CT SE 2, Michael Stal
Architecture
2
TECHNOLOGY Lifecycle Contract
Lifecycle
...
Interface
OnActivation()
OnPassivation()
Component
invoke
CONTAINER
...
WhoIsTheCaller()
AccessDatabase() invoke Component
LocateComponent()
CONTAINER
SERVICES
Software &
Engineering 6 © Siemens AG, CT SE 2, Michael Stal
Architecture
3
TECHNOLOGY Environmental Contract
Component X
Metainfo X
4. Delegate to X
SERVICE 2. Check Component‘s
Requirements
3. Provide required environment
CONTAINER
1. Invoke X
Extension Contract
TECHNOLOGY
CONTAINER
Software &
Engineering 8 © Siemens AG, CT SE 2, Michael Stal
Architecture
4
TECHNOLOGY Client/Container Contract
6. Invoke
Software &
Engineering 9 © Siemens AG, CT SE 2, Michael Stal
Architecture
EB1
JavaBeans
CORPORATE
Enterprise
Java Application Information
EB2 Services
Database
EB3 Existing
appication
C++ Application
Software &
Engineering 10 © Siemens AG, CT SE 2, Michael Stal
Architecture
5
TECHNOLOGY
EJB Servers/Containers
JNDI
Naming
Service Deployment
Descriptor
1) lookup home
CORPORATE
EJB
EJB Context
2) create bean Home EJB
Jar
Home Interface
new
4
Client
EnterpriseBean
ejbCreate
EJB ejb... Bean
4) remove Instance
Object
3) Use bean Remote Interface bean-methods
EJBServer
Application Run-time
(Container)
Software &
Engineering 11 © Siemens AG, CT SE 2, Michael Stal
Architecture
2. Business Tier
TECHNOLOGY
• stateless
• stateful
• Message-driven
Bean
• Web Services with
EJBs
• Entity Bean
Software &
Engineering 12 © Siemens AG, CT SE 2, Michael Stal
Architecture
6
2. Business Tier
TECHNOLOGY
A Sample Stateful Session Bean
Software &
Engineering 13 © Siemens AG, CT SE 2, Michael Stal
Architecture
Callback Methods
}
public void ejbActivate() {...}
public void ejbPassivate() {...}
public void ejbRemove() {...}
public void ejbCreate() throws
javax.ejb.CreateException {...}
Software &
Engineering 14 © Siemens AG, CT SE 2, Michael Stal
Architecture
7
TECHNOLOGY
Deployment Descriptor for a Stateful Bean
<enterprise-beans>
<session>
CORPORATE
<ejb-name>ShoppingCartEJB</ejb-name>
<home>ShoppingCartHome</home>
<remote>ShoppingCart</remote>
<ejb-class>ShoppingCartBean</ejb-class>
<session-type>Stateful</session-type>
</session>
</enterprise-beans>
Software &
Engineering 15 © Siemens AG, CT SE 2, Michael Stal
Architecture
TECHNOLOGY
SessionContext
• Example:
boolean isManager=ctx.isCallerInRole("Manager");
if (isManager) {
…
}
Software &
Engineering 16 © Siemens AG, CT SE 2, Michael Stal
Architecture
8
2. Business Tier
TECHNOLOGY
Stateful Session Bean Client Example
(initialContext.lookup("java:comp/env/ejb/shopping-cart"),
CartHome.class);
Software &
Engineering 17 © Siemens AG, CT SE 2, Michael Stal
Architecture
2. Business Tier
TECHNOLOGY
EntityBean JDB
CORPORATE
Corba
JD
POJO
IIOP
Server
CONTAINER
Software &
Engineering 18 © Siemens AG, CT SE 2, Michael Stal
Architecture
9
TECHNOLOGY Deployment Descriptor
• In the deployment descriptor
information the bean provider must
supply information such as
• Bean name, bean class, home interface, <ejb-jar>
remote interface <enterprise-beans>
Software &
Engineering 19 © Siemens AG, CT SE 2, Michael Stal
Architecture
Software &
Engineering 20 © Siemens AG, CT SE 2, Michael Stal
Architecture
10
TECHNOLOGY Goals of EJB 3.0
• Use Meta-Data
• Use Dependency Injection
• Reducing the number of artifacts developers
must provide
CORPORATE
• Configuration by exception
• Reducing environmental dependencies
• Simplification of EJB types
• Getting rid of many interfaces
• Simplification of persistence
• Improved testing outside of the container
Software &
Engineering 21 © Siemens AG, CT SE 2, Michael Stal
Architecture
Software &
Engineering 22 © Siemens AG, CT SE 2, Michael Stal
Architecture
11
TECHNOLOGY Programming Model: Bean Class
{
public int add(long item){…}
public void remove(int id){…}
}
Software &
Engineering 23 © Siemens AG, CT SE 2, Michael Stal
Architecture
...
@PreDestroy remove() { ... }
}
Software &
Engineering 24 © Siemens AG, CT SE 2, Michael Stal
Architecture
12
TECHNOLOGY Programming Model: Interceptors
interceptor class:
• May throw runtime exceptions or application exceptions defined in throw
clause of intercepted business method
• Execute in same security/transaction context like business methods
• May invoke JNDI, JDBC, JMS, other beans and the EntityManager
• Supported by dependency injection
• Multiple interceptors may be defined for same business
method
• Within interceptor proceed() used to call actual
implementation
Software &
Engineering 25 © Siemens AG, CT SE 2, Michael Stal
Architecture
Interceptors (cont‘d)
TECHNOLOGY
Software &
Engineering 26 © Siemens AG, CT SE 2, Michael Stal
Architecture
13
TECHNOLOGY Important Annotations and Defaults (1)
{
public int add(long item);
public void remove(int id);
}
Software &
Engineering 27 © Siemens AG, CT SE 2, Michael Stal
Architecture
Software &
Engineering 28 © Siemens AG, CT SE 2, Michael Stal
Architecture
14
TECHNOLOGY Stateless Session Beans
@Stateless
• Properties: @Interceptors( {MyInterceptor.class} )
public class FlightBookingBean implements
• Implement plain Java FlightBooking {
business interfaces public void bookFlight(long flightInfo) { ... }
@PostConstruct public void Init() {
• Do not provide a home }
interface }
CORPORATE
method execution
Software &
Engineering 29 © Siemens AG, CT SE 2, Michael Stal
Architecture
Software &
Engineering 30 © Siemens AG, CT SE 2, Michael Stal
Architecture
15
TECHNOLOGY Stateful Session Bean Example (1)
Software &
Engineering 31 © Siemens AG, CT SE 2, Michael Stal
Architecture
rc.close();
cause the container to remove }
the bean after completion catch (CloseException e)
{ /* no-op */ }
}
@Remove
public void getRidOfIt() {
// whatever necessary
// before removing
}
...
Software &
Engineering 32 © Siemens AG, CT SE 2, Michael Stal
Architecture
16
TECHNOLOGY Stateful Session Bean Example (3)
monitor(InvocationContext ic) {
for every business try {
Object res = inv.proceed();
method if ((OPResult)res
==OpResult.SUCCESS) {
System.out.println(„Ok“);
}
return res;
}
catch(Exception ex) {
throw ex;
}
}
} // end of class
Software &
Engineering 33 © Siemens AG, CT SE 2, Michael Stal
Architecture
• Clients:
• Obtains session bean by lookup (JNDI)
• Or by dependency injection
• Uses special methods of a stateful session bean to initialize the bean
bacause there are no create methods anymore
CORPORATE
Software &
Engineering 34 © Siemens AG, CT SE 2, Michael Stal
Architecture
17
TECHNOLOGY Message Driven Beans
• Properties:
• Implements message-lsistener interface determined by messaging
type (e.g., javax.jms.MessageListener)
• Message driven bean class is annotated with @MessageDriven
• It does not need implementing javax.ejb.MessageDrivenBean
CORPORATE
Software &
Engineering 35 © Siemens AG, CT SE 2, Michael Stal
Architecture
import javax.ejb.MessageDriven;
import javax.ejb.ActivationConfigProperty;
import javax.jms.Message;
CORPORATE
import javax.jms.MessageListener;
@MessageDriven(activateConfig = {
@ActivationConfigProperty(propertyName="destinationType",
propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(propertyName="destination",
propertyValue="exampleQueue")
})
public class ExampleMDB implements MessageListener
{
public void onMessage(Message recvMsg)
{ /* ... */ }
}
Software &
Engineering 36 © Siemens AG, CT SE 2, Michael Stal
Architecture
18
TECHNOLOGY Bean Context and Environment (1)
@EJB (name=„mySessionBean,
beanInterface=MySessionIF.class)
@Resource(name=„DB“,
type=„javax.sql.DataSource.class)
Software &
Engineering 37 © Siemens AG, CT SE 2, Michael Stal
Architecture
Software &
Engineering 38 © Siemens AG, CT SE 2, Michael Stal
Architecture
19
TECHNOLOGY Bean Context and Environment (3)
• Setter Injection
• Is an alternative to field injection
• Container invokes setter method instead of setting instance variable
CORPORATE
@Resource(name=„myDB“)
public void setDataSource(DataSource myDB) {
this.MyDB = myDB;
}
@Resource
public void SetSessionContext(SessionContext ctx) {
this.ctx = ctx;
}
Software &
Engineering 39 © Siemens AG, CT SE 2, Michael Stal
Architecture
Persistence
TECHNOLOGY
Software &
Engineering 40 © Siemens AG, CT SE 2, Michael Stal
Architecture
20
TECHNOLOGY Example for an Entity
@Entity
@Table(name = „CustomerList")
CORPORATE
Software &
Engineering 41 © Siemens AG, CT SE 2, Michael Stal
Architecture
Primary Keys
TECHNOLOGY
Software &
Engineering 42 © Siemens AG, CT SE 2, Michael Stal
Architecture
21
TECHNOLOGY Embedded and Embeddable
@Entity
CORPORATE
@Table(name = „Customer")
public class Customer implements java.io.Serializable
{// instances and embedded objects map to one single table
privat Address addr;
...
@Embedded
@AttributeOverrides({
@AttributeOverride(name=„city“, column=@Column(name=„city“)),
@AttributeOverride(name=„country, column=@Column(name=„country))})
public Address getAddress() { return addr; }
public void setAddress(Address a) { addr = a; }
}
@Embeddable
public class Address implements java.io.Serializable {
private String city;
private String country;
Software & }
Engineering 43 © Siemens AG, CT SE 2, Michael Stal
Architecture
@Entity
CORPORATE
@Table(name = „Customer")
Customer
@SecondaryTables({
@SecondaryTable(name=„Address“)
@SecondaryTable(name=„OrderList“)})
public class Customer implements
Entity
java.io.Serializable OrderList
Customer
{
// from Customer DB
@Column(name=„name“)
public String getName() { ... } If column Address
... annotation
@Column(name=„street“, is missing,
secondaryTable=„Address“) derive from
public String getStreet(){ ... } name
}
Software &
Engineering 44 © Siemens AG, CT SE 2, Michael Stal
Architecture
22
TECHNOLOGY Entity Relationships
Software &
Engineering 45 © Siemens AG, CT SE 2, Michael Stal
Architecture
Entity Inheritance
TECHNOLOGY
Software &
Engineering 46 © Siemens AG, CT SE 2, Michael Stal
Architecture
23
TECHNOLOGY EntityManager
EntityManager API
TECHNOLOGY
Software &
Engineering 48 © Siemens AG, CT SE 2, Michael Stal
Architecture
24
TECHNOLOGY More About Entity Managers
@Stateless
@PersistenceContext(name="orderEM"
unitName="Order")
public class MySessionBean implements MyInterface {
@Resource SessionContext ctx;
public void foo() {
EntityManager em =
(EntityManager)ctx.lookup("OrderEM");
}
}
Software &
Engineering 49 © Siemens AG, CT SE 2, Michael Stal
Architecture
EntityManagerFactory emf;
• In J2SE:
EntityManagerFactory emf =
javax.persistence.Persistence.createEntityManagerFactory(
"Order");
EntityManager em = emf.createEntityManager();
Software &
Engineering 50 © Siemens AG, CT SE 2, Michael Stal
Architecture
25
TECHNOLOGY Example: Resource-Local EntityManager
import javax.persistence.*;
public class PasswordChanger {
public static void main (String[] args) {
EntityManagerFactory emf =
Persistence.createEntityManagerFactory();
CORPORATE
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
user = em.createQuery
("SELECT u FROM User u WHERE u.name=:name AND
u.pass=:pass")
.setParameter("name", args[0])
.setParameter("pass", args[1])
.getSingleResult();
if (user!=null)
user.setPassword(args[2]);
em.getTransaction().commit();
em.close(); // application ends lifecycle
emf.close ();
}
}
Software &
Engineering 51 © Siemens AG, CT SE 2, Michael Stal
Architecture
Transaction Control
TECHNOLOGY
Software &
Engineering 52 © Siemens AG, CT SE 2, Michael Stal
Architecture
26
TECHNOLOGY Persistence Contexts
Software &
Engineering 53 © Siemens AG, CT SE 2, Michael Stal
Architecture
Persistence Context
}
public Order getOrder(Long id) { return em.find(Order.class, id); }
public Product getProduct() {
return (Product) em.createQuery("select p from Product p
where p.name = :name")
.setParameter("name", name)
.getSingleResult();
}
public LineItem createLineItem(Order order, Product product, intquantity) {
em.getTransaction().begin();
LineItem li = new LineItem(order, product, quantity);
order.getLineItems().add(li);
em.persist(li);
em.getTransaction().commit();
return li;
}
public void destroy() { em.close(); emf.close();}
}
Software &
Engineering 54 © Siemens AG, CT SE 2, Michael Stal
Architecture
27
TECHNOLOGY Entity Instance Life Cycle
Error
persist()
remove()
persist()
remove()
Software &
Engineering 55 © Siemens AG, CT SE 2, Michael Stal
Architecture
@Entity
@Table(name="CUSTOMER")
@EntityListener(CustomerCallbackListener.class)
public class Customer implements java.io.Serializable {…}
public class CustomerCallbackListener{
@PrePersist public void doPrePersist(Customer customer) {...}
...
}
Software &
Engineering 56 © Siemens AG, CT SE 2, Michael Stal
Architecture
28
TECHNOLOGY Query API
Named Query
TECHNOLOGY
@NamedQuery(name=„findAllCustomersWithName“,
queryString=„SELECT c FROM customer.c WHERE
CORPORATE
Software &
Engineering 58 © Siemens AG, CT SE 2, Michael Stal
Architecture
29
TECHNOLOGY Entity Manager and Query Example
@@Stateless
@Remote(CustomerDAO.class)
public class CustomerDAOBean implements CustomerDAO {
@PersistenceContext private EntityManager manager;
public int create(String first, String last, String street, String
CORPORATE
Software &
Engineering 59 © Siemens AG, CT SE 2, Michael Stal
Architecture
30
TECHNOLOGY Entity Packaging
Software &
Engineering 61 © Siemens AG, CT SE 2, Michael Stal
Architecture
<entity-manager>
<name>em1</name>
<provider>com.acme.persistence</provider>
<jta-data-source>jdbc/MyDB</jta-data-source>
<mapping-file>ormap.xml</mapping-file>
<jar-file>MyApp.jar</jar-file>
<class>com.widgets.Order</class>
<class>com.widgets.Customer</class>
<properties>
<property name="sql-logging" value="on"/>
</properties>
</entity-manager>
Software &
Engineering 62 © Siemens AG, CT SE 2, Michael Stal
Architecture
31
TECHNOLOGY Summary
Software &
Engineering 63 © Siemens AG, CT SE 2, Michael Stal
Architecture
Resources
TECHNOLOGY
• Documents:
• JSR 220 specification (EJB Simplified API, Java Persistence API, EJB
Core Contracts and Requirements) download from
http://jcp.org/aboutJava/communityprocess/pr/jsr220/index.html
• Application Servers with alpha/beta EJB 3.0 support
CORPORATE
• JBoss: http://www.jboss.org
• Oracle: http://otn.oracle.com/ejb3
• Joint venture of Sun and Oracle: https://glassfish.dev.java.net/
• Eclipse ORM project: http://www.eclipse.org/proposals/eclipse-ejb30-
orm/index.html
Software &
Engineering 64 © Siemens AG, CT SE 2, Michael Stal
Architecture
32
TECHNOLOGY
CORPORATE Q&A
Software &
Engineering 65 © Siemens AG, CT SE 2, Michael Stal
Architecture
Software &
Engineering 66 © Siemens AG, CT SE 2, Michael Stal
Architecture
33
TECHNOLOGY BACKUP MATERIAL
• DEPENDENCY INJECTION
• EJB 2.1 ENTITY BEANS EXAMPLE
CORPORATE
Software &
Engineering 67 © Siemens AG, CT SE 2, Michael Stal
Architecture
public class A {
public B cb;
public A() { cb = get_B_Object(...); }
...
CORPORATE
}
public class B { ... }
public class Container {
public A createA() {
return new A();
}
}
• Liability:
• A depends on way to create or obtain a B instance
Software &
Engineering 68 © Siemens AG, CT SE 2, Michael Stal
Architecture
34
TECHNOLOGY Dependency Injection Example (2)
public class A {
public B cb;
public A() { ... }
CORPORATE
...
}
public class B { ... }
public class Container {
public A createA() {
A a = new A();
a.cb = get_B_Object(...);
return a;
}
}
• Benefits:
• A is not dependent anymore on how to create or obtain B instance
• This is called field injection and is normally committed by reflection
Software &
Engineering 69 © Siemens AG, CT SE 2, Michael Stal
Architecture
public class A {
protected B b1;
CORPORATE
protected B b2;
public A(B b1) { this.b1 = b1; }
public setB2(B b2) { this.b2 = b2; }
...
}
public class B { ... }
public class Container {
public A createA() {
B b1 = get_B_Object(...);
A a = new A(b1); // constructor injection
B b2 = get_B_Object(...);
a.setB2(b2); // setter aka property injection
return a;
}
}
Software &
Engineering 70 © Siemens AG, CT SE 2, Michael Stal
Architecture
35
TECHNOLOGY Dependency Injection Example (4)
public class A {
protected B b1;
CORPORATE
protected B b2;
@MyFieldInjection
public B b3;
@MyConstructorInjection
public A(B b1) { this.b1 = b1; }
@MySetterInjection
public setB2(B b2) { this.b2 = b2; }
...
}
Software &
Engineering 71 © Siemens AG, CT SE 2, Michael Stal
Architecture
TECHNOLOGY
Software &
Engineering 72 © Siemens AG, CT SE 2, Michael Stal
Architecture
36
TECHNOLOGY
A Sample Entity Bean (cont’d)
Client
CORPORATE
owner: String
currentValue: int
Owner Balance
Miller 500
Gates 500000
Bush 2000
Gore 3600 withdraw()
... ... deposit()
getBalance()
Account Component
Software &
73 © Siemens AG, CT SE 2, Michael Stal
Engineering
Architecture
Database AccountsDB
TECHNOLOGY
Software &
Engineering 74 © Siemens AG, CT SE 2, Michael Stal
Architecture
37
TECHNOLOGY
A Sample Entity Bean (cont’d): Remote Interface
import java.rmi.RemoteException;
import javax.ejb.EJBObject;
CORPORATE
Software &
Engineering 75 © Siemens AG, CT SE 2, Michael Stal
Architecture
TECHNOLOGY
import java.rmi.RemoteException;
import javax.ejb.FinderException;
import javax.ejb.CreateException;
import javax.ejb.EJBHome;
CORPORATE
Software &
Engineering 76 © Siemens AG, CT SE 2, Michael Stal
Architecture
38
TECHNOLOGY
A Sample Entity Bean (cont’d): Bean class
• signatures must match parameters of
import java.rmi.*; the home interface‘s create method
}
public void ejbLoad() {
// called after container loads persistent state
}
public void ejbStore() {
// called before container stores persistent state
}
public void ejbRemove() {
// deletes database entry
}
public void ejbActivate() {
// allocate resources
}
public void ejbPassivate() {
// deallocate resources
}
Software &
Engineering 78 © Siemens AG, CT SE 2, Michael Stal
Architecture
39
TECHNOLOGY A Sample Entity Bean (cont’d): Declarations for
Container-Managed fields
Software &
Engineering 79 © Siemens AG, CT SE 2, Michael Stal
Architecture
Implementation
public void deposit(int amount) {
setCurrentValue(getCurrentValue()+amount);
}
public void withdraw(int amount){
CORPORATE
setCurrentValue(getCurrentValue()-amount);
}
public int getBalance() {
return getCurrentValue();
}
Software &
Engineering 80 © Siemens AG, CT SE 2, Michael Stal
Architecture
40
TECHNOLOGY
A Sample Entity Bean (cont’d)
Software &
Engineering 81 © Siemens AG, CT SE 2, Michael Stal
Architecture
TECHNOLOGY
Descriptor
CORPORATE
META-INF/ejb-jar.xml
Remote Interface:
Account.class
Home Interface:
AccountHome.class
Bean Class:
AccountBean.class
...
Software &
Engineering 82 © Siemens AG, CT SE 2, Michael Stal
Architecture
41
TECHNOLOGY
A Sample Entity Bean (cont’d): ejb-jar.xml
<enterprise-beans>
<entity>
<ejb-name>AccountEJB</ejb-name>
<home>AccountHome</home>
<remote>Account</remote>
CORPORATE
<ejb-class>AccountBean</ejb-class>
<persistence-type>Container</persistence-type>
<prim-key-class>java.lang.String</prim-key-class>
<cmp-version>2.x</cmp-version>
<cmp-field ><field-name>owner</field-name></cmp-field>
<cmp-field ><field-name>currentValue</field-name></cmp-field>
<primkey-field>owner</primkey-field>
</entity>
</enterprise-beans>
Software &
Engineering 83 © Siemens AG, CT SE 2, Michael Stal
Architecture
Software &
Engineering 84 © Siemens AG, CT SE 2, Michael Stal
Architecture
42
TECHNOLOGY
A Sample Entity Bean (cont’d): Client
System.out.println(myAccount1.getBalance());
System.out.println(myAccount2.getBalance());
Software &
Engineering 85 © Siemens AG, CT SE 2, Michael Stal
Architecture
TECHNOLOGY
EJB Servers/Containers
JNDI
Naming
Deployment
Service
Descriptor
1) lookup home
CORPORATE
AccountHome
EJB
EJB EJB
2) create bean Context
Home Jar
Home Interface
new
4
Client
Account EnterpriseBeanAccountBean
ejbCreate
EJB ejb... Bean
4) remove
Object Instance
3) Use bean Remote Interface bean-methods
Software &
Engineering
Architecture
EJB86
Application Run-time
Server (Container)
© Siemens AG, CT SE 2, Michael Stal
43
TECHNOLOGY EJB Object and EJB Home
EJB Object
• implements remote interface of the enterprise bean
• wraps enterprise bean instance
CORPORATE
EJBObject
extends
Account EntityBean
implements implements
Account_EJB_Object AccountBean
references
Software &
Engineering 87 © Siemens AG, CT SE 2, Michael Stal
Architecture
TECHNOLOGY
EJB Home
EJBHome
CORPORATE
extends
AccountHome
implements
Account_EJB_Home
Software &
Engineering 88 © Siemens AG, CT SE 2, Michael Stal
Architecture
44
TECHNOLOGY EJB Object and EJB Home (cont’d)
EJB Home
• working closely with the EJB container
• responsible for locating, creating and removing enterprise beans
• Example:
CORPORATE
Software &
Engineering 89 © Siemens AG, CT SE 2, Michael Stal
Architecture
45