SlideShare a Scribd company logo
Implementing Java EE Applications using Enterprise JavaBeans (EJB) 3 Technology: Real World Tips, Tricks, and New Design Patterns Fabiane Bizinella Nardon CTO Zilics www.zilics.com TS-4721 Edgar Silva Solutions Architect JBoss, a division of Red Hat www.jboss.com
Goal Share the tips, tricks, and new design patterns we learned when developing real-world Enterprise JavaBeans™ (EJB™) 3 technology applications.
Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
EJB 3 Technology New Features POJO based Annotations support Callback methods Listeners Interceptors Dependency Injection Defaults New persistence model New query language
Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
EJB 3 technology in the real world No more Hello World or Pet Store applications, please! Some real-world projects: Enterprise Content Management for a Government Agency Project: Human Resources Information system for an IT Company Project: Healthcare Information Systems for Healthcare Providers in Brazil and Angola Project: Financial Services Sales System for a multi-national bank Project:
Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
Keep the defaults in mind! Watch out for default transaction demarcation: by default, all methods are transactional with a REQUIRED transaction attribute What to do with non-transactional methods? Use  NOT_SUPPORTED : the method won ’t have access to the transaction context Use  SUPPORTS : take care, the behavior can be different depending on the calling method Use  NEVER : can cause an error if the calling method is transactional Session Beans Pitfalls
Some pitfalls still exists Call by value vs call by reference Remote calls: pass by value Local calls: pass by reference Exceptions do not rollback transactions automatically, only system exceptions do: Call setRollbackOnly when an exception is thrown or Annotate your exception to rollback @ApplicationException(rollback=true) public class MyException extends Exception ...
Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
Entity Beans Pitfalls By default, all fields are persistent. Watch out for transient fields! Keep the defaults in mind @Transient public String getAProperty{ … } Different relationships have different default fetch type: OneToOne: EAGER OneToMany: LAZY ManyToMany: LAZY
Lazy loading relationships and tiers You should annotate your relationship properties as LAZY in most cases.  “Why?” You won’t have long queries, retrieving unnecessary objects, resulting on bad performance But there are situations when it is better to use EAGER loading: It is better to eager load the relationships your view tier is expecting, so you can avoid multiple database queries If you are not keeping the session opened, you have to initialize your relationships before passing the object to the view tier to avoid lazy loading exceptions
Detached Entities and Lazy Loading public Patient getPatientData(PK id) { Patient p = entityManager.find(id); p.getDocuments().size(); // O bjects detach automatically when they  // are serialized or when a persistence context ends. // The specification does not  define any way to  // explicitly detach objects. } public void updatePatient(Patient p) { Patient p = entityManager.merge(p); }
Retrieving meta-information You can read annotation in run-time to retrieve information about your model However, if a deployment descriptor was used, there is only one safe way to do this: public String getPrimaryKey(Class clazz, EntityManager em) { if (em instanceof  HibernateEntityManager ) {  SessionFactory factory =  ((HibernateEntityManager)em) .getSession().getSessionFactory(); String pk = factory.getClassMetadata(clazz) .getIdentifierPropertyName(); } }
Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
Message Driven Beans Pitfalls Dealing with Exceptions The Spec says:  “ Message-driven beans should not, in general, throw RuntimeExceptions ” How to rollback a transaction: Throw an Exception annotated with  “rollback=true” Catch the exception and call setRollbackOnly() Missed PreDestroy Callbacks You can n ot assume that the  PreDestroy callback method will always be invoked. It may not be executed when: The EJB technology Container crashes A system exception is thrown from the instance ’s  method to the container
Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
Using Dependency Injection You can dynamically get resources using DI, such as Connections, Persistence Contexts, Queues and others EJB technology Dependency Injection in EJB 3 technology is as easy as on Spring, even for dynamic values (env-entries). @Stateless public class SalesProcessorBean implements  SalesProcessorRemote, SalesProcessorLocal { @Resource  int maxAcceptableFails; @Resource  int minOfPositivePoints; public String executeEvaluation() {…} }
Using Dependency Injection (cont.) <enterprise-beans> <session> <ejb-name>SalesProcessorBean</ejb-name> <ejb-class>ejb.samples.di.SalesProcessorBean</ejb-class>  <env-entry> <description> The maximum of acceptable fails </description> <env-entry-name> maxAcceptableFails </env-entry-name> <env-entry-type> java.lang.Integer </env-entry-type> <env-entry-value> 5 </env-entry-value> </env-entry>
Using Interceptors AOP vs. Interceptors Interceptor acting as: Business Validation Audit  Security Issues The deployer can turn on or off the interceptors and  define the execution order
Processing annotations in runtime Annotations can be processed in runtime, what opens endless possibilities Examples: Building dynamic eager fetch queries public Object findEagerFetch(PK pk, Class object) { // find properties with lazy fetch relationship  // annotations and // build dynamic eager fetch query } Detect differences between the domain objects and the database that could be used to automatically evolve the database schema
Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
Old and New Design Patterns Old design patterns applied to EJB 3.0 technology Session Fa çade Value Object Fast Lane Reader Business Delegate Value List Handler New design patterns Business Rule Interceptor Entity View Eager Loading Parameter Data Change Observer Exportable Method Exportable Service Broker
Session Fa çade Goal: Centralize client calls to the model tier, hiding persistence technology details   @Stateless public class PatientFacadeBean implements PatientFacade {  @PersistenceContext(unitName=”PatientPC&quot;) private EntityManager em; public void addPatient(Patient p){ em.persist(p); } public List<Patient> findPatients() { List<Patient> result = em.createQuery( &quot;SELECT OBJECT(p)  “+ “ FROM Patient p&quot;).getResultList(); return result; } }
Value Object /  Data Transfer Object Usually you can pass your persistent POJOs to the next tier, but in some cases DTOs are still useful: Reduce the problems with lazy loading and detached objects, specially when the view and the persistence tiers are developed by different teams When you have large entities (lots of properties, embedded objects, large text properties, etc) and you need to decrease the amount of data transferred to another tier
Fast Lane Reader Goal: Data retrieval is done through a direct query to the database, without using EJB Entity Beans for this task. In EJB 3 technology, this pattern is almost unnecessary, unless you want to use database proprietary features and get the maximum possible performance using Java DataBase Connectivity (JDBC™) directly
Business Delegate Goal: Reduce coupling between presentation tier and business services, hiding the underlying implementation details of the business service, such as lookup and access details of the EJB architecture It still useful to hide the technology used on the service layer from the presentation layer However, dependency injection makes the client side much easier, so, unless you really need the business delegate, try to avoid it
Value List Handler Goal: to   provide a client with an iterator for a virtual list that resides in another application tier Still useful if you are using Stateless Session Beans, specially in web applications Client ValueListHandler Page SessionBean Entity <<getData>> <<iterates>> <<providesData>> 0..n <<instantiates>>
Business Rule Interceptor Problem 1: some business rules should be triggered depending on the current context Problem 2: new business rules should be added for a particular installation of your application   public void savePatientVisit(Visit v) { if(!currentUser().worksForHospital(v.getHospital) {   throw new SecurityException( “can’t save data”); } if(v.getHospital().equals( “H1”)) { runHospital1BusinessRule(v); } save(visit); }
Business Rule Interceptor (Cont.) Solution: create an interceptor to handle these rules   @Interceptors({SecurityInterceptor.class, CustomRulesInterceptor.class}) public void savePatientVisit(Visit v) { save(visit); } The interceptor can be integrated to a rules engine, such as Drools (JBoss Rules)
Entity View Problem: you have an entity bean with many properties. You want to retrieve only a few properties, so you can send a smaller object to the next tier Solution: create a query that retrieves a smaller object SELECT  NEW br.com.zilics.PatientView(p.id, p.name)   FROM Patient p  WHERE p.name LIKE  :name
Eager Loading Parameter Problem: your entity has lazy loaded relationships, so the find method will not eager load them. However, you want to be able to change this behavior when you know you ’ll need the relationships Solution: create an alternative implementation of the find method that will eager load the relationships public Object findEagerFetch(PK pk, Class object, boolean eagerLoadOneToOne,  boolean eagerLoadOneToMany, int maxFetch ); public Object findEagerFetch(PK pk, Class object, String… relationships );
Data Change Observer Problem When you update your data, you want to notify other objects on your application Solution Use Life Cycle Callback Methods on the Entity Beans and notify your observers when data changes @EntityListeners(QuoteObserver.class) public class Quote implements Serializable {…} public class QuoteObserver { @PostPersist   public void newQuoteAvailable(Quote q) {    EventSystem.alert(q.getName(), q.getValue()); }  }
Exportable Method Problem You have to export a method to a Web Service but it has too many complex data types public Proposal getProposalByCode(String code) { return em.find(Proposal, code); } @WebMethod public String getProposalByCodeAsXML(String code) {   return  XmlTransformer().marshal ( getProposalByCode (code)); }
Exportable Service Broker Problem You want to export your application to a web service, providing only one entry point Solution Create a SLSB with simple signature structure methods and use Dependency Injection to access others EJB technology.
Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
Transition impact for the developers Common mistakes of EJB 2.1 technology developers Avoiding inheritance Over-complex architectures Handling Lazy Loading
Summary EJB 3 Technology Benefits Easier development model Better object oriented development support More productivity for developers EJB 3 Technology Drawbacks Still missing an efficient standard pagination mechanism Retrieving meta-information about the domain model in runtime is not standardized Lazy loading handling still brings problems
For More Information See: Java Specification Request (JSR) 220 ( http://jcp.org/en/jsr/detail?id=220) BOF-4834—Designing Self-Evolving and Self-Configuring Java Platform, Enterprise Edition  (Java EE) Applications TS-4247—Enterprise JavaBeans 3.1 Technology Next Steps Watch the blog:  http://weblogs.java.net/blog/edgars We will be publishing a lot of stuff about  EJB 3.0 New Design Patterns.
Q&A Fabiane Bizinella Nardon (fabiane@dev.java.net) Edgar Silva ( [email_address] )

More Related Content

PPS
Coding Best Practices
PPTX
Performance Tuning with XHProf
PDF
Cracking OCA and OCP Java 8 Exams
PDF
FAQ - why does my code throw a null pointer exception - common reason #1 Rede...
PPT
Introduction to Rule-based Applications
PDF
The Art of Unit Testing - Towards a Testable Design
PPTX
OOP Day 2
PPT
Pragmatics of Declarative Ajax
Coding Best Practices
Performance Tuning with XHProf
Cracking OCA and OCP Java 8 Exams
FAQ - why does my code throw a null pointer exception - common reason #1 Rede...
Introduction to Rule-based Applications
The Art of Unit Testing - Towards a Testable Design
OOP Day 2
Pragmatics of Declarative Ajax

Similar to JavaOne 2007 - TS4721 (20)

PDF
Ejb examples
PPT
EJBDetailsFeb25.ppt
PPTX
EJB3 Basics
PPTX
Skillwise EJB3.0 training
PDF
Ejb3 Presentation
PPT
ADVANCED JAVA MODULE I & II.ppt
PPT
Session 5 Tp5
PPT
Enterprise java beans(ejb)
PPT
Enterprise Java Beans( E)
PPT
Enterprise java beans(ejb) update 2
PPT
Enterprise java beans(ejb) Update 2
PDF
Ejb3 Dan Hinojosa
ODP
EJB 3.0 Walkthrough (2006)
PPT
2 introduction toentitybeans
PDF
Ejb intro
PPT
Enterprise java beans(ejb)
PPT
Enterprise java beans(ejb) update 2
ODP
JavaEE Spring Seam
PPSX
Entity beans in java
PDF
EJB 3.0 - Yet Another Introduction
Ejb examples
EJBDetailsFeb25.ppt
EJB3 Basics
Skillwise EJB3.0 training
Ejb3 Presentation
ADVANCED JAVA MODULE I & II.ppt
Session 5 Tp5
Enterprise java beans(ejb)
Enterprise Java Beans( E)
Enterprise java beans(ejb) update 2
Enterprise java beans(ejb) Update 2
Ejb3 Dan Hinojosa
EJB 3.0 Walkthrough (2006)
2 introduction toentitybeans
Ejb intro
Enterprise java beans(ejb)
Enterprise java beans(ejb) update 2
JavaEE Spring Seam
Entity beans in java
EJB 3.0 - Yet Another Introduction

More from Edgar Silva (20)

PDF
API Methodology by Skalena
PDF
Flyweigth - Arquitetura de Referência para Open Banking Brasil Fase 1
PDF
Skalena - Finance Business Unit
PDF
Plataforma de Consentimento (LGDP) Skalena
PDF
Casos de Sucesso WSO2 no Governo Brasileiro
PDF
DevOps Tour SP 2019
PDF
Skalena - Overview de Soluções
PDF
WSO2 Governance Registry 5.4.0 - Overview
PDF
WSO2 Enterprise Integrator 6.1 - Integração na Era da Transformação
PDF
Transformação Digital de Forma Pragmatica WSO2
PDF
WSO2 Novo Modelo de Subscrições e Produtos 2017
PDF
WSO2 API Manager 2.0 - Overview
PDF
Workshop WSO2 BPS 3.5.x - BPMN
PDF
WSO2 Telco MCX
PPTX
Workshop MSF4J - Getting Started with Microservices and Java
PDF
WSO2 API Manager : Going beyond the just API Management
PDF
Workshop/Tutorial WSO2 Micro Services Server
PDF
WSO2 Micro Services Server - Basic Workshop Part 1
PDF
Conectando Turismo e Viagens - Plataforma WSO2
PDF
WSO2 Application Server como Alternativa ao Tomcat
API Methodology by Skalena
Flyweigth - Arquitetura de Referência para Open Banking Brasil Fase 1
Skalena - Finance Business Unit
Plataforma de Consentimento (LGDP) Skalena
Casos de Sucesso WSO2 no Governo Brasileiro
DevOps Tour SP 2019
Skalena - Overview de Soluções
WSO2 Governance Registry 5.4.0 - Overview
WSO2 Enterprise Integrator 6.1 - Integração na Era da Transformação
Transformação Digital de Forma Pragmatica WSO2
WSO2 Novo Modelo de Subscrições e Produtos 2017
WSO2 API Manager 2.0 - Overview
Workshop WSO2 BPS 3.5.x - BPMN
WSO2 Telco MCX
Workshop MSF4J - Getting Started with Microservices and Java
WSO2 API Manager : Going beyond the just API Management
Workshop/Tutorial WSO2 Micro Services Server
WSO2 Micro Services Server - Basic Workshop Part 1
Conectando Turismo e Viagens - Plataforma WSO2
WSO2 Application Server como Alternativa ao Tomcat

Recently uploaded (20)

PDF
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
PPTX
Dragon_Fruit_Cultivation_in Nepal ppt.pptx
PPTX
New Microsoft PowerPoint Presentation - Copy.pptx
PDF
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
PDF
How to Get Business Funding for Small Business Fast
PDF
MSPs in 10 Words - Created by US MSP Network
PDF
Solara Labs: Empowering Health through Innovative Nutraceutical Solutions
PPTX
Probability Distribution, binomial distribution, poisson distribution
PDF
Nidhal Samdaie CV - International Business Consultant
DOCX
Business Management - unit 1 and 2
PDF
IFRS Notes in your pocket for study all the time
PDF
pdfcoffee.com-opt-b1plus-sb-answers.pdfvi
PDF
BsN 7th Sem Course GridNNNNNNNN CCN.pdf
PPTX
ICG2025_ICG 6th steering committee 30-8-24.pptx
DOCX
unit 1 COST ACCOUNTING AND COST SHEET
PPTX
Lecture (1)-Introduction.pptx business communication
PPTX
5 Stages of group development guide.pptx
PPT
Chapter four Project-Preparation material
PPTX
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
PDF
20250805_A. Stotz All Weather Strategy - Performance review July 2025.pdf
Outsourced Audit & Assurance in USA Why Globus Finanza is Your Trusted Choice
Dragon_Fruit_Cultivation_in Nepal ppt.pptx
New Microsoft PowerPoint Presentation - Copy.pptx
SIMNET Inc – 2023’s Most Trusted IT Services & Solution Provider
How to Get Business Funding for Small Business Fast
MSPs in 10 Words - Created by US MSP Network
Solara Labs: Empowering Health through Innovative Nutraceutical Solutions
Probability Distribution, binomial distribution, poisson distribution
Nidhal Samdaie CV - International Business Consultant
Business Management - unit 1 and 2
IFRS Notes in your pocket for study all the time
pdfcoffee.com-opt-b1plus-sb-answers.pdfvi
BsN 7th Sem Course GridNNNNNNNN CCN.pdf
ICG2025_ICG 6th steering committee 30-8-24.pptx
unit 1 COST ACCOUNTING AND COST SHEET
Lecture (1)-Introduction.pptx business communication
5 Stages of group development guide.pptx
Chapter four Project-Preparation material
AI-assistance in Knowledge Collection and Curation supporting Safe and Sustai...
20250805_A. Stotz All Weather Strategy - Performance review July 2025.pdf

JavaOne 2007 - TS4721

  • 1. Implementing Java EE Applications using Enterprise JavaBeans (EJB) 3 Technology: Real World Tips, Tricks, and New Design Patterns Fabiane Bizinella Nardon CTO Zilics www.zilics.com TS-4721 Edgar Silva Solutions Architect JBoss, a division of Red Hat www.jboss.com
  • 2. Goal Share the tips, tricks, and new design patterns we learned when developing real-world Enterprise JavaBeans™ (EJB™) 3 technology applications.
  • 3. Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
  • 4. Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
  • 5. EJB 3 Technology New Features POJO based Annotations support Callback methods Listeners Interceptors Dependency Injection Defaults New persistence model New query language
  • 6. Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
  • 7. EJB 3 technology in the real world No more Hello World or Pet Store applications, please! Some real-world projects: Enterprise Content Management for a Government Agency Project: Human Resources Information system for an IT Company Project: Healthcare Information Systems for Healthcare Providers in Brazil and Angola Project: Financial Services Sales System for a multi-national bank Project:
  • 8. Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
  • 9. Keep the defaults in mind! Watch out for default transaction demarcation: by default, all methods are transactional with a REQUIRED transaction attribute What to do with non-transactional methods? Use NOT_SUPPORTED : the method won ’t have access to the transaction context Use SUPPORTS : take care, the behavior can be different depending on the calling method Use NEVER : can cause an error if the calling method is transactional Session Beans Pitfalls
  • 10. Some pitfalls still exists Call by value vs call by reference Remote calls: pass by value Local calls: pass by reference Exceptions do not rollback transactions automatically, only system exceptions do: Call setRollbackOnly when an exception is thrown or Annotate your exception to rollback @ApplicationException(rollback=true) public class MyException extends Exception ...
  • 11. Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
  • 12. Entity Beans Pitfalls By default, all fields are persistent. Watch out for transient fields! Keep the defaults in mind @Transient public String getAProperty{ … } Different relationships have different default fetch type: OneToOne: EAGER OneToMany: LAZY ManyToMany: LAZY
  • 13. Lazy loading relationships and tiers You should annotate your relationship properties as LAZY in most cases. “Why?” You won’t have long queries, retrieving unnecessary objects, resulting on bad performance But there are situations when it is better to use EAGER loading: It is better to eager load the relationships your view tier is expecting, so you can avoid multiple database queries If you are not keeping the session opened, you have to initialize your relationships before passing the object to the view tier to avoid lazy loading exceptions
  • 14. Detached Entities and Lazy Loading public Patient getPatientData(PK id) { Patient p = entityManager.find(id); p.getDocuments().size(); // O bjects detach automatically when they // are serialized or when a persistence context ends. // The specification does not define any way to // explicitly detach objects. } public void updatePatient(Patient p) { Patient p = entityManager.merge(p); }
  • 15. Retrieving meta-information You can read annotation in run-time to retrieve information about your model However, if a deployment descriptor was used, there is only one safe way to do this: public String getPrimaryKey(Class clazz, EntityManager em) { if (em instanceof HibernateEntityManager ) { SessionFactory factory = ((HibernateEntityManager)em) .getSession().getSessionFactory(); String pk = factory.getClassMetadata(clazz) .getIdentifierPropertyName(); } }
  • 16. Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
  • 17. Message Driven Beans Pitfalls Dealing with Exceptions The Spec says: “ Message-driven beans should not, in general, throw RuntimeExceptions ” How to rollback a transaction: Throw an Exception annotated with “rollback=true” Catch the exception and call setRollbackOnly() Missed PreDestroy Callbacks You can n ot assume that the PreDestroy callback method will always be invoked. It may not be executed when: The EJB technology Container crashes A system exception is thrown from the instance ’s method to the container
  • 18. Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
  • 19. Using Dependency Injection You can dynamically get resources using DI, such as Connections, Persistence Contexts, Queues and others EJB technology Dependency Injection in EJB 3 technology is as easy as on Spring, even for dynamic values (env-entries). @Stateless public class SalesProcessorBean implements SalesProcessorRemote, SalesProcessorLocal { @Resource int maxAcceptableFails; @Resource int minOfPositivePoints; public String executeEvaluation() {…} }
  • 20. Using Dependency Injection (cont.) <enterprise-beans> <session> <ejb-name>SalesProcessorBean</ejb-name> <ejb-class>ejb.samples.di.SalesProcessorBean</ejb-class> <env-entry> <description> The maximum of acceptable fails </description> <env-entry-name> maxAcceptableFails </env-entry-name> <env-entry-type> java.lang.Integer </env-entry-type> <env-entry-value> 5 </env-entry-value> </env-entry>
  • 21. Using Interceptors AOP vs. Interceptors Interceptor acting as: Business Validation Audit Security Issues The deployer can turn on or off the interceptors and define the execution order
  • 22. Processing annotations in runtime Annotations can be processed in runtime, what opens endless possibilities Examples: Building dynamic eager fetch queries public Object findEagerFetch(PK pk, Class object) { // find properties with lazy fetch relationship // annotations and // build dynamic eager fetch query } Detect differences between the domain objects and the database that could be used to automatically evolve the database schema
  • 23. Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
  • 24. Old and New Design Patterns Old design patterns applied to EJB 3.0 technology Session Fa çade Value Object Fast Lane Reader Business Delegate Value List Handler New design patterns Business Rule Interceptor Entity View Eager Loading Parameter Data Change Observer Exportable Method Exportable Service Broker
  • 25. Session Fa çade Goal: Centralize client calls to the model tier, hiding persistence technology details @Stateless public class PatientFacadeBean implements PatientFacade { @PersistenceContext(unitName=”PatientPC&quot;) private EntityManager em; public void addPatient(Patient p){ em.persist(p); } public List<Patient> findPatients() { List<Patient> result = em.createQuery( &quot;SELECT OBJECT(p) “+ “ FROM Patient p&quot;).getResultList(); return result; } }
  • 26. Value Object / Data Transfer Object Usually you can pass your persistent POJOs to the next tier, but in some cases DTOs are still useful: Reduce the problems with lazy loading and detached objects, specially when the view and the persistence tiers are developed by different teams When you have large entities (lots of properties, embedded objects, large text properties, etc) and you need to decrease the amount of data transferred to another tier
  • 27. Fast Lane Reader Goal: Data retrieval is done through a direct query to the database, without using EJB Entity Beans for this task. In EJB 3 technology, this pattern is almost unnecessary, unless you want to use database proprietary features and get the maximum possible performance using Java DataBase Connectivity (JDBC™) directly
  • 28. Business Delegate Goal: Reduce coupling between presentation tier and business services, hiding the underlying implementation details of the business service, such as lookup and access details of the EJB architecture It still useful to hide the technology used on the service layer from the presentation layer However, dependency injection makes the client side much easier, so, unless you really need the business delegate, try to avoid it
  • 29. Value List Handler Goal: to provide a client with an iterator for a virtual list that resides in another application tier Still useful if you are using Stateless Session Beans, specially in web applications Client ValueListHandler Page SessionBean Entity <<getData>> <<iterates>> <<providesData>> 0..n <<instantiates>>
  • 30. Business Rule Interceptor Problem 1: some business rules should be triggered depending on the current context Problem 2: new business rules should be added for a particular installation of your application public void savePatientVisit(Visit v) { if(!currentUser().worksForHospital(v.getHospital) { throw new SecurityException( “can’t save data”); } if(v.getHospital().equals( “H1”)) { runHospital1BusinessRule(v); } save(visit); }
  • 31. Business Rule Interceptor (Cont.) Solution: create an interceptor to handle these rules @Interceptors({SecurityInterceptor.class, CustomRulesInterceptor.class}) public void savePatientVisit(Visit v) { save(visit); } The interceptor can be integrated to a rules engine, such as Drools (JBoss Rules)
  • 32. Entity View Problem: you have an entity bean with many properties. You want to retrieve only a few properties, so you can send a smaller object to the next tier Solution: create a query that retrieves a smaller object SELECT NEW br.com.zilics.PatientView(p.id, p.name) FROM Patient p WHERE p.name LIKE :name
  • 33. Eager Loading Parameter Problem: your entity has lazy loaded relationships, so the find method will not eager load them. However, you want to be able to change this behavior when you know you ’ll need the relationships Solution: create an alternative implementation of the find method that will eager load the relationships public Object findEagerFetch(PK pk, Class object, boolean eagerLoadOneToOne, boolean eagerLoadOneToMany, int maxFetch ); public Object findEagerFetch(PK pk, Class object, String… relationships );
  • 34. Data Change Observer Problem When you update your data, you want to notify other objects on your application Solution Use Life Cycle Callback Methods on the Entity Beans and notify your observers when data changes @EntityListeners(QuoteObserver.class) public class Quote implements Serializable {…} public class QuoteObserver { @PostPersist public void newQuoteAvailable(Quote q) { EventSystem.alert(q.getName(), q.getValue()); } }
  • 35. Exportable Method Problem You have to export a method to a Web Service but it has too many complex data types public Proposal getProposalByCode(String code) { return em.find(Proposal, code); } @WebMethod public String getProposalByCodeAsXML(String code) { return XmlTransformer().marshal ( getProposalByCode (code)); }
  • 36. Exportable Service Broker Problem You want to export your application to a web service, providing only one entry point Solution Create a SLSB with simple signature structure methods and use Dependency Injection to access others EJB technology.
  • 37. Agenda Brief introduction to EJB 3 technology new features EJB 3 technology in the real world Session Beans Pitfalls, Tips, and Tricks Entity Beans Pitfalls, Tips, and Tricks Message Driven Beans Pitfalls, Tips, and Tricks Refactoring to better use EJB 3 technology Old and New Design Patterns Conclusion
  • 38. Transition impact for the developers Common mistakes of EJB 2.1 technology developers Avoiding inheritance Over-complex architectures Handling Lazy Loading
  • 39. Summary EJB 3 Technology Benefits Easier development model Better object oriented development support More productivity for developers EJB 3 Technology Drawbacks Still missing an efficient standard pagination mechanism Retrieving meta-information about the domain model in runtime is not standardized Lazy loading handling still brings problems
  • 40. For More Information See: Java Specification Request (JSR) 220 ( http://jcp.org/en/jsr/detail?id=220) BOF-4834—Designing Self-Evolving and Self-Configuring Java Platform, Enterprise Edition (Java EE) Applications TS-4247—Enterprise JavaBeans 3.1 Technology Next Steps Watch the blog: http://weblogs.java.net/blog/edgars We will be publishing a lot of stuff about EJB 3.0 New Design Patterns.
  • 41. Q&A Fabiane Bizinella Nardon (fabiane@dev.java.net) Edgar Silva ( [email_address] )