Overview over EJB3

info@ejb3workshop.com http://www.ejb3workshop.com
© 2006 www.ejb3workshop.com
1

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

© 2006 www.ejb3workshop.com
2

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

© 2006 www.ejb3workshop.com
3

ejb3workshop.Java 5 features Annotations Generics Auto boxing © 2006 www.com 4 .

5.sun.com/j2se/1.html © 2006 www.html . deployment descriptor or bean info See : http://java.com/j2se/1.0/docs/ guide/language/annotations.sun.com 5 Just a brief overview of Java annotations.Java 5 Annotations Defined in an interface Declared using @Annotation Accessible via reflection API Used to add meta information e.0/docs/guide/language/annotations.ejb3workshop. For more information refer to : http://java.g.5.

add(0.intValue(). ArrayList list = new ArrayList(). A collection of Integers.get(0)). list.Java 5 Generics for Collections Generics allow for typed collection which only contain objects of a particular class.add(0.get(0). 42). © 2006 www. Vehicle or Accounts. list. int total = list.com 6 . new Integer(42)). ArrayList<Integer> list = new ArrayList<Integer>(). People. int total = ((Integer)list.ejb3workshop.

ArrayList<Integer> list = new ArrayList<Integer>(). boolean) and their respective Object counterparts (Integer.Java 5 Autoboxing Automatic conversion between primitive data types (int. int total = (list.get(0). 42). int total = list. Long and Boolean) ArrayList<Integer> list = new ArrayList<Integer>(). long.intValue(). new Integer(42)). int <-> Integer .get(0)).add(0. list. © 2006 www.com 7 Conversion of primitive datatypes to their object equivalent. list.ejb3workshop.add(0.

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 © 2006 www.com 8 .ejb3workshop.

© 2006 www.Example uses of AOP Logging Security Testing Transformations Any other concern which does not directly impact on the underlying concern.ejb3workshop.com 9 .

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 © 2006 www.ejb3workshop.com 10 Discuss the advantages and disadvantages of having meta data included with code. Advantages: -Portable -Maintainable Disadvantages: -Less flexiblity as each component can only be associated to it’s meta data rather then have several meta-data associations .

com 11 ..) © 2006 www..Session Beans Stateful and Stateless Use of vanilla POJO’s plus META data Annotation of call back methods to replace ejbXYZ(.ejb3workshop.EJB3 .

ejb3workshop.Session Bean Pattern Ensures that the common services are supported by both Remote and Local ServicesInterface interfaces businessServiceA(...) businessServiceB(. .com 12 Discuss the benefits of this pattern.EJB3 ..) RemoteInterface LocalInterface BeanImplementation businessServiceA(.) businessServiceB(.) © 2006 www......

EJB3 . public double divide(double a.Serializable.com 13 .io.sessionbean.ejb3workshop.Stateless Session Bean The Services Interface package com. } © 2006 www. double b) throws CalculatorException. import java. public double subtract(double a. public interface CalculatorServices extends Serializable { public double add(double a. double b). double b). double b). public double mulitply(double a.ejb3workshop.

EJB3 .Stateless Session Bean Local Interface package com.ejb3workshop.ejb.Local. import javax.sessionbean. @Local public interface CalculatorLocal extends CalculatorServices { } © 2006 www.com 14 .ejb3workshop.

ejb3workshop.sessionbean.Stateless Session Bean Remote Interface package com. @Remote public interface CalculatorRemote extends CalculatorServices { } © 2006 www.ejb. import javax.EJB3 .com 15 .ejb3workshop.Remote.

Logger.EJB3 ... } .ejb3workshop. import javax.sessionbean.Stateless Session Bean Bean Implementation package com.logging.ejb3workshop.. public double add(double a.util. import java. CalculatorLocal { .*. double b) { ... @Stateless public class CalculatorBean implements CalculatorRemote..ejb. © 2006 www.com 16 .

com 17 .info("PRE DESTROY").ejb3workshop. } @PreDestroy public void preDestroy() { logger.Stateless Session Bean Bean Implementation continued @PostConstruct public void postConstruct() { logger.info("POST CONSTRUCT"). } } © 2006 www.EJB3 .

} © 2006 www.4)). System. CalculatorServices calculator = (CalculatorServices)o. import javax.util...} } . import javax.ejb3workshop..add(5.sessionbean. .ejb3workshop.printStackTrace().ejb.EJBException.out..lookup(”CalculatorBean/remote”).println("ADD : "+calculator.com 18 . Object o = ctx. } catch (Exception e){e.EJB3 Client Code package com.*.naming. import java. public class Client { public void runTest() { try { InitialContext ctx = new InitialContext().*.

com 19 .ejb3workshop.Stateless Lifecycle @PostCreate Ready Pooled @PostDestroy Destroyed © 2006 www.

ejb3workshop. } . import javax. @Stateful public class CalculatorBean implements CalculatorRemote..*.ejb3workshop. public double add(double a..ejb.Logger.. import java..sessionbean.. © 2006 www.EJB3 .Stateful Session Bean Bean Implementation package com.. CalculatorLocal { .util.logging.com 20 . double b) { .

The name of the method is up to the developer as only the annotations are required. } @PrePassivate public void prePassivate() { .EJB3 . in particular in relation to the client..com 21 Highlight the importance of the @Remove method.. } @PostActivate public void postActivate() { ...Stateful Session Bean Bean Implementation continued @Remove public double getResult() { . } © 2006 www.. ..ejb3workshop.

Stateful Lifecycle
Passivated @PrePassivate @PostActivate @PostCreate Ready Pooled @PostDestroy

Destroyed

© 2006 www.ejb3workshop.com
22

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

© 2006 www.ejb3workshop.com
23

EJB3 Interceptors
Specifies a single interceptor method per bean via @AroundInvoke in the bean itself Specific method signature
@AroundInvoke public Object customInterceptor(InvocationContext ctx) throws Exception {
System.out.println("*** BEFORE INTERCEPTION ***"); Object object = ctx.proceed(); System.out.println("*** AFTER INTERCEPTION ***"); return object; }

© 2006 www.ejb3workshop.com
24

Dog.ejb3workshop..EJB3 Interceptors Specifies a series of interceptor which are invoked sequentially import javax.. @Interceptors ({com. © 2006 www.*.class}) @Stateless public class MailManBean implements MailManRemote.interceptor.sessionbean.ejb.com 25 .ejb3workshop. MailManLocal { .

println("*** BEFORE INTERCEPTION ***").*.EJB3 Interceptors Interception handled in external class Same method signature as before package com. Object object = ctx. } } © 2006 www. import javax. public class Dog { @AroundInvoke public Object intercept(InvocationContext ctx) throws Exception { System.println("*** AFTER INTERCEPTION ***").sessionbean. return object.out.ejb3workshop.interceptor.ejb.proceed(). System.ejb3workshop.com 26 .out.

ejb3workshop.Interception Sequence Client "EJB Container" add(1.com 27 .1) External Interceptor Internal Interceptor Method Bean Business Logic @AroundInvoke @AroundInvoke add(1.1) return 2 return 2 return 2 © 2006 www.

ejb3workshop. AspectWerks or alternate AOP implementation © 2006 www.EJB3 Interceptors Only provide interceptors for all methods of a particular bean Consider and investigate AspectJ.com 28 .

ejb3workshop... © 2006 www.com 29 .Q&A Next Section Entity Beans.

ejb3workshop. with minor modifications Ability to map to existing data model / database schema © 2006 www.com 30 .EJB3 .Entity Beans Single defined layer for persistence Reuse of persistent classes in business and presentation layer Use POJO as persistent component.

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 © 2006 www.com 31 .EJB3 .ejb3workshop.

© 2006 www. .com 32 The primary key class must define equals and hashCode methods.Entity Example Standard POJO Added Annotation Should provide implementation for equals and hashCode. 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. Can be specialisation of common “super” entity.EJB .ejb3workshop.

@Column(name="name") public String getName(){return name.} /*..} public void setName(String name){this.Serializable { private String name. @Entity @Table(name="Contacts") public class Contact implements java.} public void setSurname(String surname){this.util.*.persistence.ejb3workshop.io. private String surname.addressbook.surname = surname.com 33 Highlight the purpose of implementing serializable and the ability to reuse the entity within other layers / tiers . import javax.} @Column(name="surname") public String getSurname(){return surname. import java..ejb3workshop.*.equals and hash should also be implemented */ } © 2006 www.Entity Example package com.name = name.

. deleting (remove) Annotated in Session Beans as @PersistenceContext © 2006 www. updating (merging). If the entity manager is used outside the container it has to be created / accessed by other means.Entity Manager Once the entities have been defined the “Entity Manger” is used to interact with the “Persistence Context”.ejb3workshop. The entity manager is responsible for the persistence of the entity and provides services for : persisting (creation).com 34 Explain the injection mechanism and highlight that is used to access the containers entity manager for session beans.

com 35 . © 2006 www. but never multiple concurrent transactions.ejb3workshop.Persistence Context Persistence context represent a collection of persistent entities Scoped around a single transaction. but can be extended to beyond that.

merge(contact). } } © 2006 www.remove(contact).ejb3workshop. public void addContact(Contact contact) { manager. } public void updateContact(Contact contact) { manager.persist(contact).Entity Manager Example @Stateful public class AddressBookBean implements AddressBookRemote. } public void deleteContact(Contact contact) { manager.com 36 . AddressBookLocal { @PersistenceContext private EntityManager manager.

} public void deleteContact(Contact contact) { manager.remove(contact).persist(contact).merge(contact). } © 2006 www.ejb3workshop. } public Contact updateContact(Contact contact) { manager.Entity Manager Useful to return entity after create / update public Contact addContact(Contact contact) { manager. return contact.com 37 . return contact.

return contacts.name = :contactName"). query = query.getResultList().com 38 .name).ejb3workshop.createQuery and manager.Entity Manager . } © 2006 www.setParameter("contactName".createQuery("Select c from Contact c where c.createNativeQuery public Collection<Contact> findContact(String name) { Query query = null. query = manager.Queries Support for EQL and SQL queries via manager. List contacts = query.

refresh / manager.Entity Lifecycle constructor New manager.ejb3workshop.merge detached Detached © 2006 www.remove manager.persist() Managed manager.com 39 .

ejb3workshop.com 40 .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 © 2006 www.

ejb3workshop.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 © 2006 www.com 41 .

1. Developers may choose whether or not to update references held by the inverse side when the owning side changes. including Abstract entities Support for embedded objects © 2006 www. • For many-to-many bidirectional relationships either side may be the owning side.2. 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.com 42 Extract form Section : 2. hence the mappedBy element cannot be specified on the ManyToOne annotation.3 Synchronization to the Database Bidirectional relationships between managed entities will be persisted based on references held by the owning side of the relationship. • The many side of one-to-many / many-to-one bidirectional relationships must be the owning side.ejb3workshop.EJB3 ." .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.One One . The mappedBy element designates the property or field in the entity that is the owner of the relationship.Entity Relationships One .Many Inheritance. OneToMany. so as to ensure the changes are not lost when they are synchronized to the database.Many Many . depending on whether the application can handle out-of-date references on the inverse side until the next database refresh occurs. the owning side corresponds to the side that contains the corresponding foreign key. • For one-to-one bidirectional relationships. Extract form Section : 3. or ManyToMany annotation. It is particularly important to ensure that changes to the inverse side of a relationship result in appropriate updates on the owningside.

a = a. TableA contains a foreign key to table B. Unidirectional OneToOne Relationships The following mapping defaults apply: Entity A is mapped to a table namedA.ejb3workshop. Entity B is mapped to a table namedB. } public void setA(A a) { this.com 43 Bidirectional OneToOne Relationships Assuming that: Entity A references a single instance of Entity B. } } } @Entity public class B { private A a. @OneToOne(mappedBy="b") public A getA() { return a.One . 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. © 2006 www. . @OneToOne public B getB() { return b.b = b. } public void setB(B b) { this.One @Entity public class A { private B b. } A is the owner of the relationship as B contains the mappedBy annotation For one-to-one bidirectional relationships. Entity B is mapped to a table namedB. Table A contains a foreign key to table B. the owning side corresponds to the side that contains the corresponding foreign key.

com 44 Bidirectional ManyToOne / OneToMany Relationships Assuming that: Entity A references a single instance of Entity B. Entity A must be the owner of the relationship. . @ManyToOne public A getA() { return a. The following mapping defaults apply: Entity A is mapped to a table namedA. 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. } } @Entity public class B { private A a. } public void setBs(Collection<B> b) { this. bees = b. hence the mappedBy element cannot be specified on the ManyToOne annotation.a = a. @OneToMany (mappedBy="a") public Collection<B> getBs() { return bees. Entity B references a collection of Entity A.ejb3workshop. } } B must be the owner of the relationship as it is the many side of the relationship The many side of one-to-many / many-to-one bidirectional relationships must be the owning side.One .Many @Entity public class A { private Collection<B> bees. Entity B is mapped to a table namedB. Table A contains a foreign key to table B. } public void setContact(A a) { this. © 2006 www.

} public void setBs(Collection<B> b) { this. @ManyToMany public Collection<B> getBs() { return bees. © 2006 www.as = a. Entity A is the owner of the relationship.ejb3workshop. There is a join table that is named A_B (owner name first). } } @Entity public class B { private Collection<A> as.com 45 Bidirectional ManyToMany Relationships Assuming that: Entity A references a collection of Entity B. Entity B is mapped to a table namedB.Many . } public void setAs(Collection<A> a) { this. There is a join table that is named A_B (owner name first). } } A is the owner of the relationship as B contains the mappedBy annotation For many-to-many bidirectional relationships either side may be the owning side. The following mapping defaults apply: Entity A is mapped to a table namedA. Entity B references a collection of Entity A. EntityB is mapped to a table namedB. Unidirectional ManyToMany Relationships The following mapping defaults apply: EntityA is mapped to a table namedA.bees = b.Many @Entity public class A { private Collection<B> bees. @ManyToMany (mappedBy="b") public Collection<A> getAs() { return as. .

com 46 Mapping inheritance using Single Table Strategy.Single Table Strategy Vehicle color RacingCar topSpeed Bus numberOfPassengers Boat length Vehicle Table Color Top Speed Number of Passengers Length Vehicle Type © 2006 www. The specification requires this strategy to be supported by all implementation. . Other implementation are optional.EJB3 .ejb3workshop.

Single Table Strategy @Entity @Inheritance(strategy = InheritanceType.ejb3workshop. discriminatorType = DiscriminatorType.Serializable @Entity @Inheritance(strategy = InheritanceType.io.SINGLE_TABLE.STRING.STRING) @DiscriminatorColumn(name = "VEHICLETYPE") public class Vehicles implements java.SINGLE_TABLE. discriminatorType = DiscriminatorType. discriminatorValue = "CAR") public class Car extends Vehicles © 2006 www.com 47 .

com 48 Each class is mapped onto it’s own table.Table per Class Strategy Vehicle color RacingCar topSpeed Bus numberOfPassengers Boat length Vehicle Table Color RacingCar Table Color TopSpeed Bus Table Color Number Of Passengers Boat Table Color Length © 2006 www.ejb3workshop. This major downside of this strategy is a duplication of data and potential long term maintenance problems.EJB3 . .

Table per Class Strategy @Entity @Inheritance(strategy = InheritanceType.com 49 .Serializable @Entity public class Car extends Vehicles © 2006 www.io.TABLE_PER_CLASS) public class Vehicles implements java.ejb3workshop.

The “superclass” is referenced by a foreign key.Join Strategy Vehicle color RacingCar topSpeed Bus numberOfPassengers Boat length Vehicle Table Color RacingCar Table VehicleID TopSpeed Bus Table VehicleID Number Of Passengers Boat Table VehicleID Length © 2006 www.com 50 With the Join Strategy there is not redundant data.ejb3workshop. This option is similar to the super reference in Java. .EJB3 .

The “superclass” is referenced by a foreign key.Join Strategy Vehicle color RacingCar topSpeed Bus numberOfPassengers Boat length Vehicle Table Color RacingCar Table VehicleID TopSpeed Bus Table VehicleID Number Of Passengers Boat Table VehicleID Length © 2006 www. This option is similar to the super reference in Java.com 50 With the Join Strategy there is not redundant data.ejb3workshop. .EJB3 .

JOINED) public class Car extends Vehicle © 2006 www.com 51 Highlight potential abstract superclass .Serializable @Entity @Inheritance(strategy = InheritanceType.io.Join Strategy @Entity @Inheritance(strategy = InheritanceType.JOINED) public class Vehicle implements java.ejb3workshop.

ejb3workshop.EAGER.The related object is loaded on demand from the database.EJB3 .ALL. Allows for prefetching of frequently used objects. Eager .The related object is also fetched from the database. mappedBy="contact") © 2006 www.Fetch Strategy Two fetch strategies are available for relationships. Lazy . Allows for on demand loading of rarely used objects @OneToMany(cascade = CascadeType.com 52 . fetch = FetchType.

mappedBy="contact") © 2006 www.EJB3 . The default is no cascading behaviour ALL. PERSIST.ALL.EAGER. REMOVE and REFRESH @OneToMany(cascade = CascadeType. MERGE. fetch = FetchType.ejb3workshop.com 53 Highlight how aggregation and composition could assist in determining what cascade type to use.Cascade Strategy The Cascade Strategy can be customised for entity relationships by including the cascade constraint in the the relationship annotation. .

com 54 Can also be handled by external class specified via @EntityListener(XYZ.class) .Entity Callbacks Similar to the callback’s used on the session beans we can annotate methods using the following: @PrePersist @PostPersist @PreRemove @PostRemove © 2006 www.ejb3workshop.

Entity Callbacks @PreUpdate @PostUpdate @PostLoad © 2006 www.class) .ejb3workshop.com 55 Can also be handled by external class specified via @EntityListener(XYZ.

Specifying NONE indicates that no primary key generation by the persistence provider should occur. This specification does not define the exact behaviour of these strategies. NONE The TABLE strategy indicates that the persistence provider should assign identifiers using an underlying database table to ensure uniqueness. such as : TABLE. AUTO indicates that the persistence provider should pick an appropriate strategy for the particular database.Primary Key Generators A primary key which can now be generated as a new instance is created. AUTO. The SEQUENCE and IDENTITY strategies specify the use of a database sequence or identity column. @Id @GeneratedValue(strategy=GenerationType.id = id. . and that the application will be responsible for assigning the primary key.com 56 Generator Type has various options.ejb3workshop. respectively. } © 2006 www. SEQUENCE. IDENTITY.AUTO) @Column(name="id") public int getId() { return id. } public void setId(int id) { this.EJB3 .

Each instance has a specific version. An exception is thrown when the version of the instance has been updated (incremented) by another party. 57 . The version is incremented during each update.Optimistic Locking Optimistic Locking is achieved via the addition of a version attribute to each bean.EJB3 .

} public void setVersion(int version) { this. applications that map the Version property to a table other than the primary table are not portable.Optimistic Locking Example @Version public int getVersion() { return version. } 58 The Version annotation specifies the version property (optimistic lock value) of an entity class. applications that use more than one are not expected to be portable. . Only a single Version property / field should be used per class. Fields or properties that are specified with the Version annotation should not be updated by the application.version=version. This is used to ensure integrity when reattaching and for overall optimistic concurrency control. The Version property should be mapped to the primary table for the entity class.

com 59 . @ActivationConfigProperty(propertyName="destination".Message Driven Beans Asynchronous Messaging @MessageDriven(activateConfig = { @ActivationConfigProperty(propertyName="destinationType".jms. © 2006 www.ejb3workshop. propertyValue="javax...Queue"). propertyValue="queue/ejb3/demo") }) public class ExampleMDB implements MessageListener { public void onMessage(Message recvMsg) .EJB3 .

html © 2006 www.org/aspectj/ http://www.com 60 .jboss.com/developer/ technicalArticles/releases/j2se15/ http://eclipse.sun.com http://java.Useful references http://ejb3workshop.java.com/products/ejb3 http://today.net/pub/a/today/2004/06/15/ ejb3.ejb3workshop.

com 61 .ejb3workshop.Q&A Thank you © 2006 www.