EJB 3.0 Peter Antman, CTO, 2006 - 2007 Mogul
EJB 3.0 - fundamentals <ul><li>Presents a simplified programming and packing model </li><ul><li>Based on POJO-programming:...
Simplified requirements on business interfaces </li></ul><li>Uses meta data annotations to do </li><ul><li>configuration
dependency injection of resources, such as other EJB:s or Data Sources
life cycle callbacks </li></ul><li>Default values for configurations used whenever possible: “Configure by exception”
Introduce object/relational mapping persistence API which works on simple domain object (inspired by Hibernate) </li></ul>...
security
resource management
remoting </li></ul></ul>
Whats new – an overview <ul><li>No more CMP and BMP beans
An Object/Relational persistence specification: Java Persistence API (JPA)
Session- and message driven beans are ordinary Java Beans: no inheritance from javax.ejb. beans
No requirement to implement callback interfaces
No more home interfaces
Remote business interface is an ordinary interface, no need to extend java.rmi.Remote
No need for remote methods to throw RemoteException
Local business interface is an ordinary interface
Bean should/may implement its interfaces
Simplified Exception handling by reducing need of checked exceptions
Business and lifecycle interceptors </li></ul>
Session beans - basic <ul><li>A session beans is an ordinary bean implementing an interface and has a @Stateless or @State...
Add @Remote to interface or bean to make the interface Remote </li></ul>@Stateless @Remote public class MyBean implements ...
Session bean – local and remote interface <ul><li>A session bean may have both a local and a remote interface
These may  not  be the same interface
They may however inherit a common parent
Annotation may be in interfaces </li></ul>@Remote public interface MyRemote extends My { } @Local public interface MyLocal...
Session bean lifecycle callbacks <ul><li>Session beans may use annotation to declare lifecycle callback interceptor method...
All session beans may use @PostConstruct and @PreDestroy </li></ul>@PostConstruct public void init() {} @PreDestroy public...
Message Driven Bean <ul><li>No need to implement javax.ejb.MessageDrivenBean
Supports @PostConstruct and @PreDestroy annotation
May use @MessageDriven annotation to configure itself
May use one or more @ActivationConfigProperty annotation for configuration </li></ul>@MessageDriven(activationConfig = { @...
Upcoming SlideShare
Loading in …5
×

EJB 3.0 Walkthrough (2006)

2,220 views

Published on

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

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,220
On SlideShare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

EJB 3.0 Walkthrough (2006)

  1. 1. EJB 3.0 Peter Antman, CTO, 2006 - 2007 Mogul
  2. 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. 3. Simplified requirements on business interfaces </li></ul><li>Uses meta data annotations to do </li><ul><li>configuration
  4. 4. dependency injection of resources, such as other EJB:s or Data Sources
  5. 5. life cycle callbacks </li></ul><li>Default values for configurations used whenever possible: “Configure by exception”
  6. 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. 7. security
  8. 8. resource management
  9. 9. remoting </li></ul></ul>
  10. 10. Whats new – an overview <ul><li>No more CMP and BMP beans
  11. 11. An Object/Relational persistence specification: Java Persistence API (JPA)
  12. 12. Session- and message driven beans are ordinary Java Beans: no inheritance from javax.ejb. beans
  13. 13. No requirement to implement callback interfaces
  14. 14. No more home interfaces
  15. 15. Remote business interface is an ordinary interface, no need to extend java.rmi.Remote
  16. 16. No need for remote methods to throw RemoteException
  17. 17. Local business interface is an ordinary interface
  18. 18. Bean should/may implement its interfaces
  19. 19. Simplified Exception handling by reducing need of checked exceptions
  20. 20. Business and lifecycle interceptors </li></ul>
  21. 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. 22. Add @Remote to interface or bean to make the interface Remote </li></ul>@Stateless @Remote public class MyBean implements My
  23. 23. Session bean – local and remote interface <ul><li>A session bean may have both a local and a remote interface
  24. 24. These may not be the same interface
  25. 25. They may however inherit a common parent
  26. 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. 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. 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. 29. Message Driven Bean <ul><li>No need to implement javax.ejb.MessageDrivenBean
  30. 30. Supports @PostConstruct and @PreDestroy annotation
  31. 31. May use @MessageDriven annotation to configure itself
  32. 32. May use one or more @ActivationConfigProperty annotation for configuration </li></ul>@MessageDriven(activationConfig = { @ActivationConfigProperty(propertyName=&quot;destinationType&quot;, propertyValue=&quot;javax.jms.Queue&quot;), @ActivationConfigProperty(propertyName=&quot;destination&quot;, propertyValue=&quot;queue/mdb&quot;) }) public class CalculatorBean implements MessageListener { public void onMessage (Message msg) {
  33. 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. 34. May be injected as </li><ul><li>an attribute (public, protected, private)
  35. 35. a setter (public, protected, private) </li></ul><li>Uses reasonable defaults
  36. 36. Have optional attributes
  37. 37. @javax.ejb.EJB injects references to other session beans
  38. 38. @javax.annotation.Resource injects resources such as environment entries or data base connections
  39. 39. @Resource may also be used to get an EJB context injected </li></ul>
  40. 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. 41. Resource injection <ul><li>Resources are injected from the java:comp/env local JNDI environment
  42. 42. Defaults to simple naming scheme (CLASSNAME/FIELDNAME)
  43. 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=&quot;jdbc/__default&quot;, type=javax.sql.DataSource.class) public class StatelessSessionBean <ul><li>Injecting it </li></ul>@Resource(name=&quot;jdbc/__default&quot;) DataSource myDs; <ul><li>Lookup any resource from JNDI (app-server specific) </li></ul>@Resource(mappedName=”my/jndi/ref) MyCustom custom;
  44. 44. Context injection <ul><li>setSessionContext has disappeared
  45. 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. 46. Transactions <ul><li>Transactions and security may also be declared by using annotations
  47. 47. Defaults to REQUIRED
  48. 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. 49. Security <ul><li>The allowed roles are defined with the annotations javax.annotation.security 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. 50. Interceptors <ul><li>Application developers may “hook” into the container by defining interceptor
  51. 51. An interceptor intercept/filters calls to bean business methods
  52. 52. An interceptor is annotated with @javax.interceptor.AroundInvoke
  53. 53. An interceptor intercepts all methods that has not excluded interception
  54. 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. 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. 56. Exceptions <ul><li>As before: </li><ul><li>system exceptions (java.lang.RuntimeException and java.rmi.RemoteException cases rollback
  57. 57. all application exceptions do not cause rollback </li></ul><li>New annotations for exceptions @javax.ejb.ApplicationException
  58. 58. Declares both ordinary and RuntimeExceptions as application exceptions
  59. 59. Declarative statement if an application exception shall cause a rollback </li></ul>@ApplicationException(rollback=true) MyAppException extends RuntimeException {
  60. 60. Java Persistence API <ul><li>JSR 220 Java Persistence API for EJB 3.0
  61. 61. Defines a </li><ul><li>Object/Relational mapping metadata
  62. 62. API for persistence
  63. 63. a query language </li></ul><li>May be used both in a JEE environment or standalone
  64. 64. Building blocks </li><ul><li>One or more Entities
  65. 65. Metadata annotations (or xml file)
  66. 66. EntityManager
  67. 67. Query
  68. 68. persistence.xml </li></ul></ul>
  69. 69. Entity <ul><li>Entity beans are plain Java objects that </li></ul><ul><ul><li>can be allocated with new
  70. 70. must have a public no arg constructor
  71. 71. have JavaBeans properties
  72. 72. supports inheritance and polymorphism
  73. 73. persistent state represented by instance variables
  74. 74. Must have a primary key
  75. 75. can be attached/detached/reattached to persistence storage.
  76. 76. are annotated with at least @Entity and @Id annotation
  77. 77. May have the following relationships to other entities </li></ul></ul><ul><ul><ul><li>one-to-one
  78. 78. one-to-many
  79. 79. many-to-one
  80. 80. many-to-many </li></ul></ul></ul>
  81. 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) {this.id = id;} public String getFirstName() { return firstName;} public void setFirstName(String fn) {this.firstName = fn;} //... }
  82. 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) {this.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. 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. 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. 85. Entity Callback annotations <ul><li>@PrePersist
  86. 86. @PostPersist
  87. 87. @PostLoad
  88. 88. @PreUpdate
  89. 89. @PostUpdate
  90. 90. @PreRemove
  91. 91. @PostRemove </li></ul>
  92. 92. Entity Listeners <ul><li>May add listeners on entity callback events
  93. 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. 94. EntityManager <ul><li>Entity beans are not remotable
  95. 95. must be access through the new javax.persistence.EntityManager service
  96. 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. 97. An entity is managed as long it is attached to a persistence context
  98. 98. When a persistence context is closed all entities it manages becomes detatched
  99. 99. A persistence context is only valid during a transaction, its is closed when transaction commits </li></ul>
  100. 100. Extended Persistence Context <ul><li>An extended persistence context manages all its bean across several transactions
  101. 101. The beans are not detached
  102. 102. Its possible to follow lazy relations
  103. 103. In EJB it may only be used in stateful session beans
  104. 104. The extended context is closed when the stateful bean is removed </li></ul>@PersistenceContext(type=PersistenceContextType.EXTENDED) private EntityManager manager;
  105. 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. 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. 107. Using the Query API <ul><li>Object oriented query language
  108. 108. Create a query from en EntityManager </li></ul>Query q = em.createQuery(“from My m where c.value = 'myval'”); 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. 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. 110. INNER JOIN
  111. 111. LEFT JOIN
  112. 112. Fetch Joins (prefetch lazy relations)
  113. 113. DISTINCT
  114. 114. LIKE
  115. 115. MEMBER OF (a collection)
  116. 116. Functional expressions such as LOWER, UPPER
  117. 117. ORDER BY, GROUP BY, HAVING
  118. 118. Subqueries
  119. 119. Bulk update and delete
  120. 120. Native Queries </li></ul></ul>
  121. 121. Locking <ul><li>Locking is no longer handled by the container
  122. 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. 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='new value', 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. 124. persistence.xml <ul><li>Only required deployment descriptor: persistence.xml </li></ul><persistence version=&quot;1.0&quot; xmlns=&quot;http://java.sun.com/xml/ns/persistence&quot;> <persistence-unit name=&quot;jsf-jpa-war&quot; transaction-type=&quot;JTA&quot;> <jta-data-source>jdbc/__default</jta-data-source> <properties> <property name=&quot;toplink.ddl-generation&quot; value=&quot;drop-and-create-tables&quot;/> </properties> </persistence-unit> </persistence>
  125. 125. mogul .slut på presentation Kontakt: [email_address]

×