62
© 2006 www.ejb3workshop.com Overview over EJB3 [email protected] http://www.ejb3workshop.com 1

EJB3Introduction

Embed Size (px)

Citation preview

© 2006 www.ejb3workshop.com

Current State of EJB3

Current specification in “Proposed Final Draft” stage 19th December 2005.

Implementations already available from various vendors, e.g. JBoss, Glassfish

http://java.sun.com/products/ejb/docs.html

2

© 2006 www.ejb3workshop.com

What’s new ?

Simplification

Based on standards and existing practices

RAD cycle

Focus on business functionality rather then piping and framework

Uses many “new” Java 5 features

3

© 2006 www.ejb3workshop.com

Annotations

Generics

Auto boxing

Java 5 features

4

© 2006 www.ejb3workshop.com

Java 5 Annotations

Defined in an interface

Declared using @Annotation

Accessible via reflection API

Used to add meta information e.g. deployment descriptor or bean info

See : http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html

5

Just a brief overview of Java annotations. For more information refer to :http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html

© 2006 www.ejb3workshop.com

Java 5 Generics for Collections

Generics allow for typed collection which only contain objects of a particular class. A collection of Integers, People, Vehicle or Accounts.ArrayList list = new ArrayList();list.add(0, new Integer(42)); int total = ((Integer)list.get(0)).intValue();

ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, 42);int total = list.get(0);

6

© 2006 www.ejb3workshop.com

Java 5 Autoboxing

Automatic conversion between primitive data types (int, long, boolean) and their respective Object counterparts (Integer, Long and Boolean)ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, new Integer(42)); int total = (list.get(0)).intValue();

ArrayList<Integer> list = new ArrayList<Integer>();list.add(0, 42);int total = list.get(0);

7

Conversion of primitive datatypes to their object equivalent. int <-> Integer

© 2006 www.ejb3workshop.com

Aspect Oriented Programming

Separation of functional and non-functional concerns or aspects

Non functional concerns are removed from non-functional

Additional feature can be added at a later on by added new aspects without affecting functional aspects

8

© 2006 www.ejb3workshop.com

Example uses of AOP

Logging

Security

Testing

Transformations

Any other concern which does not directly impact on the underlying concern.

9

© 2006 www.ejb3workshop.com

EJB3 and META data

Inline META data

External META data (deployment descriptor)

Both have pro’s and con’s

Lost ability to deploy same bean in multiple contexts

Gained maintainability and portability

10

Discuss the advantages and disadvantages of having meta data included with code. Advantages:-Portable-MaintainableDisadvantages:-Less flexiblity as each component can only be associated to it’s meta data rather then have several meta-data associations

© 2006 www.ejb3workshop.com

EJB3 - Session Beans

Stateful and Stateless

Use of vanilla POJO’s plus META data

Annotation of call back methods to replace ejbXYZ(...)

11

© 2006 www.ejb3workshop.com

EJB3 - Session Bean Pattern

Ensures that the common services are supported by both Remote and Local interfaces ServicesInterface

businessServiceA(...)businessServiceB(...)

RemoteInterface LocalInterface

BeanImplementationbusinessServiceA(...)businessServiceB(...)

12

Discuss the benefits of this pattern.

© 2006 www.ejb3workshop.com

EJB3 - Stateless Session Bean

The Services Interface

package com.ejb3workshop.sessionbean; import java.io.Serializable;

public interface CalculatorServices extends Serializable{ public double add(double a, double b); public double subtract(double a, double b); public double mulitply(double a, double b); public double divide(double a, double b) throws CalculatorException;}

13

© 2006 www.ejb3workshop.com

EJB3 - Stateless Session Bean

Local Interfacepackage com.ejb3workshop.sessionbean;import javax.ejb.Local;

@Localpublic interface CalculatorLocal extends CalculatorServices {}

14

© 2006 www.ejb3workshop.com

EJB3 - Stateless Session Bean

Remote Interfacepackage com.ejb3workshop.sessionbean;import javax.ejb.Remote;

@Remotepublic interface CalculatorRemote extends CalculatorServices{}

15

© 2006 www.ejb3workshop.com

EJB3 - Stateless Session Bean

Bean Implementationpackage com.ejb3workshop.sessionbean;import java.util.logging.Logger;import javax.ejb.*;@Statelesspublic class CalculatorBean implements CalculatorRemote, CalculatorLocal{ ... public double add(double a, double b) { ... }...

16

© 2006 www.ejb3workshop.com

EJB3 - Stateless Session Bean

Bean Implementation continued @PostConstruct public void postConstruct() { logger.info("POST CONSTRUCT"); } @PreDestroy public void preDestroy() { logger.info("PRE DESTROY"); }}

17

© 2006 www.ejb3workshop.com

EJB3 Client Codepackage com.ejb3workshop.sessionbean;import java.util.*;import javax.ejb.EJBException;import javax.naming.*;

public class Client { public void runTest() { try { InitialContext ctx = new InitialContext(); Object o = ctx.lookup(”CalculatorBean/remote”); CalculatorServices calculator = (CalculatorServices)o; System.out.println("ADD : "+calculator.add(5,4)); ... } catch (Exception e){e.printStackTrace();} }...}

18

© 2006 www.ejb3workshop.com

Stateless Lifecycle

Ready Pooled

@PostCreateDestroyed

@PostDestroy

19

© 2006 www.ejb3workshop.com

EJB3 - Stateful Session Bean

Bean Implementationpackage com.ejb3workshop.sessionbean;import java.util.logging.Logger;import javax.ejb.*;@Statefulpublic class CalculatorBean implements CalculatorRemote, CalculatorLocal{ ... public double add(double a, double b) { ... }...

20

© 2006 www.ejb3workshop.com

EJB3 - Stateful Session Bean

Bean Implementation continued @Remove public double getResult() { ... } @PostActivate public void postActivate() { ... } @PrePassivate public void prePassivate() { ... }

21

Highlight the importance of the @Remove method, in particular in relation to the client. The name of the method is up to the developer as only the annotations are required.

© 2006 www.ejb3workshop.com

Stateful Lifecycle

Ready Pooled

@PostCreateDestroyed

@PostDestroy

Passivated

@PrePassivate

@PostActivate

22

© 2006 www.ejb3workshop.com

EJB Interceptors

Implementation of basic AOP

Less capable then AspectJ or AspectWerks

Allows only for interceptor delegation to other methods and / or other classes.

Affects all services offered by the bean

23

© 2006 www.ejb3workshop.com

EJB3 Interceptors

Specifies a single interceptor method per bean via @AroundInvoke in the bean itself

Specific method signature@AroundInvokepublic Object customInterceptor(InvocationContext ctx) throws Exception{ System.out.println("*** BEFORE INTERCEPTION ***"); Object object = ctx.proceed(); System.out.println("*** AFTER INTERCEPTION ***"); return object;}

24

© 2006 www.ejb3workshop.com

EJB3 Interceptors

Specifies a series of interceptor which are invoked sequentially

import javax.ejb.*;

@Interceptors ({com.ejb3workshop.sessionbean.interceptor.Dog.class})@Statelesspublic class MailManBean implements MailManRemote, MailManLocal{...

25

© 2006 www.ejb3workshop.com

EJB3 Interceptors

Interception handled in external class

Same method signature as beforepackage com.ejb3workshop.sessionbean.interceptor; import javax.ejb.*;public class Dog { @AroundInvoke public Object intercept(InvocationContext ctx) throws Exception { System.out.println("*** BEFORE INTERCEPTION ***"); Object object = ctx.proceed(); System.out.println("*** AFTER INTERCEPTION ***"); return object; }}

26

© 2006 www.ejb3workshop.com

Interception SequenceClient External

InterceptorInternal

Interceptor Method

Bean Business Logic

"EJB Container"

add(1,1)

@AroundInvoke

@AroundInvoke

add(1,1)

return 2

return 2

return 2

27

© 2006 www.ejb3workshop.com

EJB3 Interceptors

Only provide interceptors for all methods of a particular bean

Consider and investigate AspectJ, Aspect-Werks or alternate AOP implementation

28

© 2006 www.ejb3workshop.com

Q & A

Next Section Entity Beans...

29

© 2006 www.ejb3workshop.com

EJB3 - Entity Beans

Single defined layer for persistence

Reuse of persistent classes in business and presentation layer

Use POJO as persistent component, with minor modifications

Ability to map to existing data model / database schema

30

© 2006 www.ejb3workshop.com

EJB3 - Entity Beans

Optimistic Locking via versioning

Support for relationships

Support for association and composition

Support for inheritance and polymorphic collections

Primary Key generation

Query language and SQL support

31

© 2006 www.ejb3workshop.com

EJB - Entity Example

Standard POJO

Added Annotation

Should provide implementation for equals and hashCode.

Can be specialisation of common “super” entity.

32The primary key class must define equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.

© 2006 www.ejb3workshop.com

Entity Examplepackage com.ejb3workshop.addressbook;import java.util.*;import javax.persistence.*;

@Entity@Table(name="Contacts")public class Contact implements java.io.Serializable{ private String name; private String surname; @Column(name="name") public String getName(){return name;} public void setName(String name){this.name = name;} @Column(name="surname") public String getSurname(){return surname;} public void setSurname(String surname){this.surname = surname;} /*...equals and hash should also be implemented */}

33

Highlight the purpose of implementing serializable and the ability to reuse the entity within other layers / tiers

© 2006 www.ejb3workshop.com

Entity ManagerOnce the entities have been defined the “Entity Manger” is used to interact with the “Persistence Context”.

The entity manager is responsible for the persistence of the entity and provides services for : persisting (creation), updating (merging), deleting (remove)

Annotated in Session Beans as @PersistenceContext

34

Explain the injection mechanism and highlight that is used to access the containers entity manager for session beans. If the entity manager is used outside the container it has to be created / accessed by other means.

© 2006 www.ejb3workshop.com

Persistence Context

Persistence context represent a collection of persistent entities

Scoped around a single transaction, but can be extended to beyond that, but never multiple concurrent transactions.

35

© 2006 www.ejb3workshop.com

@Statefulpublic class AddressBookBean implements AddressBookRemote, AddressBookLocal{ @PersistenceContext private EntityManager manager; public void addContact(Contact contact) { manager.persist(contact); } public void updateContact(Contact contact) { manager.merge(contact); } public void deleteContact(Contact contact) { manager.remove(contact); }}

Entity Manager Example

36

© 2006 www.ejb3workshop.com

Useful to return entity after create / update

public Contact addContact(Contact contact) { manager.persist(contact); return contact; } public Contact updateContact(Contact contact) { manager.merge(contact); return contact; } public void deleteContact(Contact contact) { manager.remove(contact); }

Entity Manager

37

© 2006 www.ejb3workshop.com

Entity Manager - Queries

Support for EQL and SQL queries via manager.createQuery and manager.createNativeQuery

public Collection<Contact> findContact(String name){ Query query = null; query = manager.createQuery("Select c from Contact c where c.name = :contactName"); query = query.setParameter("contactName",name); List contacts = query.getResultList(); return contacts;}

38

© 2006 www.ejb3workshop.com

Entity Lifecycle

Newconstructor

Managed

Detached

manager.persist()

manager.re

fresh /

manager.m

erg

edeta

ched

manager.remove

39

© 2006 www.ejb3workshop.com

Entity States

New: The entity is created but not attached to the persistence context

Managed: The entity has been attached and is now added to the persistence context

State changes synchronised with backend

Transparent association are fetched

40

© 2006 www.ejb3workshop.com

Entity States

Detached: The entity has been passed outside the container

No longer managed by container

State changes to be managed manually

Transparent fetch of associations no longer supported

Removed: Deleted from persistence context

41

© 2006 www.ejb3workshop.com

EJB3 - Entity Relationships

One - One

One - Many

Many - Many

Inheritance, including Abstract entities

Support for embedded objects

42

Extract form Section : 2.1.7 Entity Relationships The following rules apply to bidirectional relationships: • The inverse side of a bidirectional relationship must refer to its owning side by use of the mappedBy element of the OneToOne, OneToMany, or ManyToMany annotation. The mappedBy element designates the property or field in the entity that is the owner of the relationship. • The many side of one-to-many / many-to-one bidirectional relationships must be the owning side, hence the mappedBy element cannot be specified on the ManyToOne annotation.

• For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.

• For many-to-many bidirectional relationships either side may be the owning side.

Extract form Section : 3.2.3 Synchronization to the Database Bidirectional relationships between managed entities will be persisted based on references held by the owning side of the relationship. It is the developer’s responsibility to keep the in-memory references held on the owning side and those held on the inverse side consistent with each other when they change. It is particularly important to ensure that changes to the inverse side of a relationship resultin appropriate updates on the owningside, so as to ensure the changes are not lost when they are synchronized to the database. Developers may choose whether or not to update references held by the inverse side when the owning side changes, depending on whether the application can handle out-of-date references on the inverse side until the next database refresh occurs."

© 2006 www.ejb3workshop.com

One - One

@Entitypublic class A{

private B b;@OneToOnepublic B getB(){

return b;} public void setB(B b){

this.b = b;}

}

@Entitypublic class B{

private A a;@OneToOne(mappedBy="b")public A getA(){

return a;} public void setA(A a){

this.a = a;}

}

A is the owner of the relationship as B contains the mappedBy annotationFor one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign

key.

43

Bidirectional OneToOne Relationships Assuming that: Entity A references a single instance of Entity B. Entity B references a single instance of Entity A. Entity A is specified as the owner of the relationship. The following mapping defaults apply: Entity A is mapped to a table namedA. Entity B is mapped to a table namedB. TableA contains a foreign key to table B.

Unidirectional OneToOne Relationships The following mapping defaults apply: Entity A is mapped to a table namedA. Entity B is mapped to a table namedB. Table A contains a foreign key to table B.

© 2006 www.ejb3workshop.com

One - Many@Entitypublic class A{private Collection<B> bees;@OneToMany (mappedBy="a")public Collection<B> getBs(){ return bees;} public void setBs(Collection<B> b){ this. bees = b;}}

@Entitypublic class B{private A a;@ManyToOnepublic A getA(){ return a;}

public void setContact(A a){ this.a = a;}}

B must be the owner of the relationship as it is the many side of the relationshipThe many side of one-to-many / many-to-one bidirectional relationships must be the owning

side, hence the mappedBy element cannot be specified on the ManyToOne annotation.

44

Bidirectional ManyToOne / OneToMany Relationships Assuming that: Entity A references a single instance of Entity B. Entity B references a collection of Entity A. Entity A must be the owner of the relationship. The following mapping defaults apply: Entity A is mapped to a table namedA. Entity B is mapped to a table namedB. Table A contains a foreign key to table B.

Unidirectional ManyToOne Relationships The following mapping defaults apply: Entity A is mapped to a table namedA. Entity B is mapped to a table namedB. Table A contains a foreign key to table B.

© 2006 www.ejb3workshop.com

Many - Many

@Entitypublic class A{private Collection<B> bees;@ManyToManypublic Collection<B> getBs(){ return bees;} public void setBs(Collection<B> b){ this.bees = b;}}

@Entitypublic class B{private Collection<A> as;@ManyToMany (mappedBy="b")public Collection<A> getAs(){ return as;} public void setAs(Collection<A> a){ this.as = a;}}

A is the owner of the relationship as B contains the mappedBy annotationFor many-to-many bidirectional relationships either side may be the owning side.

45

Bidirectional ManyToMany Relationships Assuming that: Entity A references a collection of Entity B. Entity B references a collection of Entity A. Entity A is the owner of the relationship. The following mapping defaults apply: Entity A is mapped to a table namedA. Entity B is mapped to a table namedB. There is a join table that is named A_B (owner name first).

Unidirectional ManyToMany Relationships The following mapping defaults apply: EntityA is mapped to a table namedA. EntityB is mapped to a table namedB. There is a join table that is named A_B (owner name first).

© 2006 www.ejb3workshop.com

EJB3 - Single Table Strategy

Vehiclecolor

RacingCartopSpeed

BusnumberOfPassengers

Boatlength

Vehicle Table

Color Top SpeedNumber of

PassengersLength Vehicle Type

46

Mapping inheritance using Single Table Strategy. The specification requires this strategy to be supported by all implementation. Other implementation are optional.

© 2006 www.ejb3workshop.com

Single Table Strategy

@Entity@Inheritance(strategy = InheritanceType.SINGLE_TABLE, discriminatorType = DiscriminatorType.STRING)@DiscriminatorColumn(name = "VEHICLETYPE")public class Vehicles implements java.io.Serializable

@Entity@Inheritance(strategy = InheritanceType.SINGLE_TABLE, discriminatorType = DiscriminatorType.STRING, discriminatorValue = "CAR")public class Car extends Vehicles

47

© 2006 www.ejb3workshop.com

EJB3 - Table per Class Strategy

Vehiclecolor

RacingCartopSpeed

BusnumberOfPassengers

Boatlength

Color

Vehicle Table

Color

RacingCar Table

TopSpeed Color

Bus Table

Number Of Passengers

Color

Boat Table

Length

48

Each class is mapped onto it’s own table. This major downside of this strategy is a duplication of data and potential long term maintenance problems.

© 2006 www.ejb3workshop.com

Table per Class Strategy

@Entity@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)public class Vehicles implements java.io.Serializable

@Entitypublic class Car extends Vehicles

49

© 2006 www.ejb3workshop.com

EJB3 - Join StrategyVehicle

color

RacingCartopSpeed

BusnumberOfPassengers

Boatlength

Color

Vehicle Table

VehicleID

RacingCar Table

TopSpeed VehicleID

Bus Table

Number Of Passengers

VehicleID

Boat Table

Length

50

With the Join Strategy there is not redundant data. The “superclass” is referenced by a foreign key. This option is similar to the super reference in Java.

© 2006 www.ejb3workshop.com

EJB3 - Join StrategyVehicle

color

RacingCartopSpeed

BusnumberOfPassengers

Boatlength

Color

Vehicle Table

VehicleID

RacingCar Table

TopSpeed VehicleID

Bus Table

Number Of Passengers

VehicleID

Boat Table

Length

50

With the Join Strategy there is not redundant data. The “superclass” is referenced by a foreign key. This option is similar to the super reference in Java.

© 2006 www.ejb3workshop.com

Join Strategy

@Entity@Inheritance(strategy = InheritanceType.JOINED)public class Vehicle implements java.io.Serializable

@Entity@Inheritance(strategy = InheritanceType.JOINED)public class Car extends Vehicle

51

Highlight potential abstract superclass

© 2006 www.ejb3workshop.com

EJB3 - Fetch Strategy

Two fetch strategies are available for relationships.

Eager - The related object is also fetched from the database. Allows for prefetching of frequently used objects.

Lazy - The related object is loaded on demand from the database. Allows for on -demand loading of rarely used objects

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="contact")

52

© 2006 www.ejb3workshop.com

EJB3 - Cascade Strategy

The Cascade Strategy can be customised for entity relationships by including the cascade constraint in the the relationship annotation.

The default is no cascading behaviour

ALL, PERSIST, MERGE, REMOVE and REFRESH

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="contact")

53

Highlight how aggregation and composition could assist in determining what cascade type to use.

© 2006 www.ejb3workshop.com

Entity Callbacks

Similar to the callback’s used on the session beans we can annotate methods using the following:

@PrePersist

@PostPersist

@PreRemove

@PostRemove

54

Can also be handled by external class specified via @EntityListener(XYZ.class)

© 2006 www.ejb3workshop.com

Entity Callbacks

@PreUpdate

@PostUpdate

@PostLoad

55

Can also be handled by external class specified via @EntityListener(XYZ.class)

© 2006 www.ejb3workshop.com

EJB3 - Primary Key Generators

A primary key which can now be generated as a new instance is created.

@Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="id") public int getId() { return id; } public void setId(int id) { this.id = id; }

56Generator Type has various options, such as : TABLE, SEQUENCE, IDENTITY, AUTO, NONEThe TABLE strategy indicates that the persistence provider should assign identifiers using an underlying database table to ensure uniqueness. The SEQUENCE and IDENTITY strategies specify the use of a database sequence or identity column, respectively. AUTO indicates that the persistence provider should pick an appropriate strategy for the particular database. Specifying NONE indicates that no primary key generation by the persistence provider should occur, and that the application will be responsible for assigning the primary key. This specification does not define the exact behaviour of these strategies.

EJB3 - Optimistic Locking

Optimistic Locking is achieved via the addition of a version attribute to each bean. Each instance has a specific version. The version is incremented during each update.

An exception is thrown when the version of the instance has been updated (incremented) by another party.

57

Optimistic Locking Example

@Version public int getVersion() { return version; } public void setVersion(int version) { this.version=version; }

58The Version annotation specifies the version property (optimistic lock value) of an entity class. This is used to ensure integrity when reattaching and for overall optimistic concurrency control. Only a single Version property / field should be used per class; applications that use more than one are not expected to be portable. The Version property should be mapped to the primary table for the entity class; applications that map the Version property to a table other than the primary table are not portable.

Fields or properties that are specified with the Version annotation should not be updated by the application.

© 2006 www.ejb3workshop.com

EJB3 - Message Driven Beans

Asynchronous Messaging@MessageDriven(activateConfig ={ @ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"), @ActivationConfigProperty(propertyName="destination", propertyValue="queue/ejb3/demo")})

public class ExampleMDB implements MessageListener{ public void onMessage(Message recvMsg) ...

59

© 2006 www.ejb3workshop.com

Q & A

Thank you

61