• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
JavaOne 2007 - TS4721
 

JavaOne 2007 - TS4721

on

  • 4,257 views

JavaOne technical session 4721, speakers: Fabiane Nardon & Edgar Silva

JavaOne technical session 4721, speakers: Fabiane Nardon & Edgar Silva

Statistics

Views

Total Views
4,257
Views on SlideShare
4,123
Embed Views
134

Actions

Likes
4
Downloads
0
Comments
0

5 Embeds 134

http://edgarsilva.com.br 98
http://www.edgarsilva.com.br 33
http://66.102.9.104 1
http://www.slideshare.net 1
http://www.linkedin.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

JavaOne 2007 - TS4721 JavaOne 2007 - TS4721 Presentation Transcript

  • 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] )