Your SlideShare is downloading. ×
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
EJB 3.0 Walkthrough (2006)
Upcoming SlideShare
Loading in...5

Thanks for flagging this SlideShare!

Oops! An error has occurred.

Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

EJB 3.0 Walkthrough (2006)


Published on

A walk through of all new features in EJB 3.0 from 2006 - 2007

A walk through of all new features in EJB 3.0 from 2006 - 2007

Published in: Technology
1 Like
  • Be the first to comment

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

No notes for slide


  • 1. EJB 3.0 Peter Antman, CTO, 2006 - 2007 Mogul
  • 2. EJB 3.0 - fundamentals <ul><li>Presents a simplified programming and packing model </li><ul><li>Based on POJO-programming: </li><ul><li>no programmatic dependencies on framework classes
  • 3. Simplified requirements on business interfaces </li></ul><li>Uses meta data annotations to do </li><ul><li>configuration
  • 4. dependency injection of resources, such as other EJB:s or Data Sources
  • 5. life cycle callbacks </li></ul><li>Default values for configurations used whenever possible: “Configure by exception”
  • 6. Introduce object/relational mapping persistence API which works on simple domain object (inspired by Hibernate) </li></ul><li>Is still an “Enterprise” platform that offers stable handling of </li><ul><li>transactions
  • 7. security
  • 8. resource management
  • 9. remoting </li></ul></ul>
  • 10. Whats new – an overview <ul><li>No more CMP and BMP beans
  • 11. An Object/Relational persistence specification: Java Persistence API (JPA)
  • 12. Session- and message driven beans are ordinary Java Beans: no inheritance from javax.ejb. beans
  • 13. No requirement to implement callback interfaces
  • 14. No more home interfaces
  • 15. Remote business interface is an ordinary interface, no need to extend java.rmi.Remote
  • 16. No need for remote methods to throw RemoteException
  • 17. Local business interface is an ordinary interface
  • 18. Bean should/may implement its interfaces
  • 19. Simplified Exception handling by reducing need of checked exceptions
  • 20. Business and lifecycle interceptors </li></ul>
  • 21. Session beans - basic <ul><li>A session beans is an ordinary bean implementing an interface and has a @Stateless or @Stateful annotation </li></ul>public interface My { public void doWork(Work w); } @Stateless public class MyBean implements My { public void doWork(Work w) {} } <ul><li>This will declare the bean a stateless session bean with a local business interface My
  • 22. Add @Remote to interface or bean to make the interface Remote </li></ul>@Stateless @Remote public class MyBean implements My
  • 23. Session bean – local and remote interface <ul><li>A session bean may have both a local and a remote interface
  • 24. These may not be the same interface
  • 25. They may however inherit a common parent
  • 26. Annotation may be in interfaces </li></ul>@Remote public interface MyRemote extends My { } @Local public interface MyLocal extends My {} <ul><li>or in bean class </li></ul>@Sateless @Remote(MyRemote.class) @Local(MyLocal.class) public class MyBean extends My {
  • 27. Session bean lifecycle callbacks <ul><li>Session beans may use annotation to declare lifecycle callback interceptor methods to receive notifications of life cycle events
  • 28. All session beans may use @PostConstruct and @PreDestroy </li></ul>@PostConstruct public void init() {} @PreDestroy public void destroy() {} <ul><li>A stateful session may also get callback during activation from or deactivation to temporary storage with @PostActivate and @PrePassivate </li></ul>@PostActivate public void activate() {} @PrePassivate public void passivate() {} <ul><li>A stateful bean may also declare a business method to be the last in a conversation with the @Remove annotation (i.e the stateful bean is removed when call ends) </li></ul>@Remove public void saveCart() {}
  • 29. Message Driven Bean <ul><li>No need to implement javax.ejb.MessageDrivenBean
  • 30. Supports @PostConstruct and @PreDestroy annotation
  • 31. May use @MessageDriven annotation to configure itself
  • 32. May use one or more @ActivationConfigProperty annotation for configuration </li></ul>@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName=&amp;quot;destinationType&amp;quot;, propertyValue=&amp;quot;javax.jms.Queue&amp;quot;), @ActivationConfigProperty(propertyName=&amp;quot;destination&amp;quot;, propertyValue=&amp;quot;queue/mdb&amp;quot;) }) public class CalculatorBean implements MessageListener { public void onMessage (Message msg) {
  • 33. Dependency injection <ul><li>By declaring dependencies on other EJB:s, resources or context a bean will get references to these injected at runtime
  • 34. May be injected as </li><ul><li>an attribute (public, protected, private)
  • 35. a setter (public, protected, private) </li></ul><li>Uses reasonable defaults
  • 36. Have optional attributes
  • 37. @javax.ejb.EJB injects references to other session beans
  • 38. @javax.annotation.Resource injects resources such as environment entries or data base connections
  • 39. @Resource may also be used to get an EJB context injected </li></ul>
  • 40. EJB injection <ul><li>Injecting an EJB attribute </li></ul>@EJB private MyLocal myLocal; <ul><li>Injecting an EJB method </li></ul>@EJB public void setMy(MyLocal myLocal) {} <ul><li>Specify a name and interface </li></ul>@EJB(beanName=”MySubBean”, beanInterface=MyLocal.class) private My my; <ul><li>Specify a direct JNDI-name </li></ul>@EJB(mappedName=”ear-name/MyBean/remote) private My my;
  • 41. Resource injection <ul><li>Resources are injected from the java:comp/env local JNDI environment
  • 42. Defaults to simple naming scheme (CLASSNAME/FIELDNAME)
  • 43. Injection of simple environmental entries (env-entry) </li></ul>@Resource int maxFoo = 5; <ul><li>Declaring a data base resource </li></ul>@Resource(name=&amp;quot;jdbc/__default&amp;quot;, type=javax.sql.DataSource.class) public class StatelessSessionBean <ul><li>Injecting it </li></ul>@Resource(name=&amp;quot;jdbc/__default&amp;quot;) DataSource myDs; <ul><li>Lookup any resource from JNDI (app-server specific) </li></ul>@Resource(mappedName=”my/jndi/ref) MyCustom custom;
  • 44. Context injection <ul><li>setSessionContext has disappeared
  • 45. Contexts are injected when needed </li></ul>@Resource SessionContext ctx; @Resource MessageDrivenContext ctx; <ul><li>Its also possoble to get a UserTransaction injected </li></ul>@Resource private UserTransaction utx;
  • 46. Transactions <ul><li>Transactions and security may also be declared by using annotations
  • 47. Defaults to REQUIRED
  • 48. May be set as default for a bean </li></ul>@TransactionAttribute(NOT_SUPPORTED) public class MyBean <ul><li>And overriden on a method base </li></ul>@TransactionAttribute(REQUIRED) public void save()
  • 49. Security <ul><li>The allowed roles are defined with the annotations AllowedRoles and PermitAll </li></ul>@AllowedRoles(“USERS”); public class MyBean { @AllowAll public List list() { @AllowedRoles(“ADMIN”) public delete() { } <ul><li>The RunAs annotation establishes the identity a bean will have when it call other beans </li></ul>@RunAs(“PRIVELIGED_USERS”); public class MyBean {
  • 50. Interceptors <ul><li>Application developers may “hook” into the container by defining interceptor
  • 51. An interceptor intercept/filters calls to bean business methods
  • 52. An interceptor is annotated with @javax.interceptor.AroundInvoke
  • 53. An interceptor intercepts all methods that has not excluded interception
  • 54. An interceptor may be defined as a method in a bean </li></ul>@Stateless public class MyBean { @AroundInvoke public Object log(InvocationContext inv) throws Exception { // Do stuff return inv.proceed(); }
  • 55. Interceptors (cont) <ul><li>Or in its own class </li></ul>public class PasswordValidator { @AroundInvoke public Object validate(InvocationContext inv) {} <ul><li>And be references from bean, either from class </li></ul>@Interceptors({PasswordValidator.class}) public class MyBean { <ul><li>Or on a specific method </li></ul>@Interceptors(PasswordValidator) public void changePassword(String old, String newP, String cmp) { <ul><li>Interceptors may be excluded on class and method level </li></ul>@ExcludeDefaultInterceptors public class MyBean @ExcludeClassInterceptor public void pure() {
  • 56. Exceptions <ul><li>As before: </li><ul><li>system exceptions (java.lang.RuntimeException and java.rmi.RemoteException cases rollback
  • 57. all application exceptions do not cause rollback </li></ul><li>New annotations for exceptions @javax.ejb.ApplicationException
  • 58. Declares both ordinary and RuntimeExceptions as application exceptions
  • 59. Declarative statement if an application exception shall cause a rollback </li></ul>@ApplicationException(rollback=true) MyAppException extends RuntimeException {
  • 60. Java Persistence API <ul><li>JSR 220 Java Persistence API for EJB 3.0
  • 61. Defines a </li><ul><li>Object/Relational mapping metadata
  • 62. API for persistence
  • 63. a query language </li></ul><li>May be used both in a JEE environment or standalone
  • 64. Building blocks </li><ul><li>One or more Entities
  • 65. Metadata annotations (or xml file)
  • 66. EntityManager
  • 67. Query
  • 68. persistence.xml </li></ul></ul>
  • 69. Entity <ul><li>Entity beans are plain Java objects that </li></ul><ul><ul><li>can be allocated with new
  • 70. must have a public no arg constructor
  • 71. have JavaBeans properties
  • 72. supports inheritance and polymorphism
  • 73. persistent state represented by instance variables
  • 74. Must have a primary key
  • 75. can be attached/detached/reattached to persistence storage.
  • 76. are annotated with at least @Entity and @Id annotation
  • 77. May have the following relationships to other entities </li></ul></ul><ul><ul><ul><li>one-to-one
  • 78. one-to-many
  • 79. many-to-one
  • 80. many-to-many </li></ul></ul></ul>
  • 81. Simple entity which uses default values @Entity public class Person implements Serializable { private long id; private String firstName; private String lastName; @Id public long getId(){ return id;} public void setId(long id) { = id;} public String getFirstName() { return firstName;} public void setFirstName(String fn) {this.firstName = fn;} //... }
  • 82. More complex entity @Entity @Table(name=”PERSON_TABLE”, uniqueConstraints=”PERSON_MAIL”) public class Person implements Serializable { //... @Id @GeneratedValue public long getId(){ return id;} public void setId(long id) { = id;} @Column(name=”PERSON_FIRST”, nullable=false, length=20) @Basic(fetch=FetchType.LAZY) public String getFirstName() { return firstName;} public void setFirstName(String fn) {this.firstName = fn;} //... @OneToOne(fetch=FetchType.LAZY) @JoinColumn(name=”ADDRESS_ID”) public Address getAddres() {} }
  • 83. The seven relatationships <ul><li>one-to-one unidirectional </li><ul><li>@OneToOne </li></ul><li>one-to-one bidirectional </li><ul><li>@OneToOne(mappedBy=”otherEndProperty”) </li></ul><li>one-to-many unidirectional </li><ul><li>@OneToMany </li></ul><li>one-to-many bidirectional (works both ways) </li><ul><li>@ManyToOne
  • 84. @OneToMany(mappedBy=”otherEndProperty) </li></ul><li>many-to-one unidirectional </li><ul><li>@ManyToOne </li></ul><li>many-to-many unidirectional </li><ul><li>@ManyToMany </li></ul><li>many-to-many bidirectional </li><ul><li>@ManyToMany(mappedBy=”otherEndProperty”) </li></ul></ul>
  • 85. Entity Callback annotations <ul><li>@PrePersist
  • 86. @PostPersist
  • 87. @PostLoad
  • 88. @PreUpdate
  • 89. @PostUpdate
  • 90. @PreRemove
  • 91. @PostRemove </li></ul>
  • 92. Entity Listeners <ul><li>May add listeners on entity callback events
  • 93. In its own classes or on bean direct </li></ul>public class Notifyer { @PostPersist void postSave(Object entity) {} } <ul><li>@EntityListeners used to add listener on an entity </li></ul>@Entity @EntityListeners(Notifyer.class) public class MyEntity { @PostLoad void afterLoad() {}
  • 94. EntityManager <ul><li>Entity beans are not remotable
  • 95. must be access through the new javax.persistence.EntityManager service
  • 96. Typically injected with @PersistenceContext annotation </li></ul>@PersistenceContext private EntityManager manager; <ul><li>May be used in session beans, message driven beans, interceptors, JSF managed beans, servlets
  • 97. An entity is managed as long it is attached to a persistence context
  • 98. When a persistence context is closed all entities it manages becomes detatched
  • 99. A persistence context is only valid during a transaction, its is closed when transaction commits </li></ul>
  • 100. Extended Persistence Context <ul><li>An extended persistence context manages all its bean across several transactions
  • 101. The beans are not detached
  • 102. Its possible to follow lazy relations
  • 103. In EJB it may only be used in stateful session beans
  • 104. The extended context is closed when the stateful bean is removed </li></ul>@PersistenceContext(type=PersistenceContextType.EXTENDED) private EntityManager manager;
  • 105. EntityManager usage <ul><li>Persist – queue for flush </li></ul>em.persist(entity); <ul><li>Find an entity </li></ul>My m = em.find(My.class, primaryKey); // null if not found My m em.getReference(My.class, primaryKey); // exception if not found <ul><li>Updating an entity inside a transaction (its still managed my tx) </li></ul>entity.setValue(newValue); <ul><li>Re-atatche entity – queue for flush </li></ul>entity.setValue(newValue); My copy = em.merge(entity); <ul><li>Remove an entity – queue for flush </li></ul>em.remove(entity); <ul><li>Refresh entity from backend </li></ul>em.refresh(entity); <ul><li>Check if entity is managed </li></ul>boolean isManaged = em.contains(entity);
  • 106. EntityManager usage (cont) <ul><li>Clear context from all entities (de-tatche) </li></ul>em.clear(); <ul><li>Manually flush/save state to backend (done automatically at least in commit of transaction) </li></ul>em.flush(); <ul><li>Only flush at commit not before any queries (flush manually only for needed queries) </li></ul>em.setFlushMode(FlushModeType.COMMIT); <ul><li>When all else fail, get implementation, eg: </li></ul>Session ses = (Session)em.getDelegate( );
  • 107. Using the Query API <ul><li>Object oriented query language
  • 108. Create a query from en EntityManager </li></ul>Query q = em.createQuery(“from My m where c.value = &apos;myval&apos;”); Query q = em.createNamedQuery(“myQuery”); // defined in annotation Query q = em.createNativeQuery(“select * from my”); <ul><li>Get the result </li></ul>List mys = q.getResultList(); <ul><li>Use parameters </li></ul>Query q = em.createQuery(“from My m where c.value=:value ”); q.setParameter(“value”, “myval”); <ul><li>Set paging </li></ul>q.setMaxResults(MAX).setFirstResult(index);
  • 109. Using the Query API (cont) <ul><li>Support fine grained queries </li></ul>Query q = em.createQuery(“SELECT m.value FROM My AS m”); <ul><li>Support object creation from queries </li></ul>SELECT new my.pack.ValueHolder(m.value) FROM My AS m <ul><li>Supports </li><ul><li>IN
  • 110. INNER JOIN
  • 111. LEFT JOIN
  • 112. Fetch Joins (prefetch lazy relations)
  • 113. DISTINCT
  • 114. LIKE
  • 115. MEMBER OF (a collection)
  • 116. Functional expressions such as LOWER, UPPER
  • 118. Subqueries
  • 119. Bulk update and delete
  • 120. Native Queries </li></ul></ul>
  • 121. Locking <ul><li>Locking is no longer handled by the container
  • 122. Delegated by default to database </li><ul><li>set isolation level in a vendor specific way </li></ul><li>Possible to use support for optimistic locking design pattern and programmatic pessimistic locking
  • 123. Use the @Version annotation in an Entity makes it handled optimistically </li></ul>@Version protected long getVersion() {...} protected void setVersion(long version) {...} update MY_BEAN set value=&apos;new value&apos;, version = version + 1 where id = ID and version = LAST <ul><li>Or use programattic locking in EntityManager </li></ul>em.lock(myEntity, LockModeType.WRITE); // or READ <ul><li>(May by spec only be supported in Entities with a @Version property) </li></ul>
  • 124. persistence.xml <ul><li>Only required deployment descriptor: persistence.xml </li></ul>&lt;persistence version=&amp;quot;1.0&amp;quot; xmlns=&amp;quot;;quot;&gt; &lt;persistence-unit name=&amp;quot;jsf-jpa-war&amp;quot; transaction-type=&amp;quot;JTA&amp;quot;&gt; &lt;jta-data-source&gt;jdbc/__default&lt;/jta-data-source&gt; &lt;properties&gt; &lt;property name=&amp;quot;toplink.ddl-generation&amp;quot; value=&amp;quot;drop-and-create-tables&amp;quot;/&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt;
  • 125. mogul .slut på presentation Kontakt: [email_address]