EJB 3

From sheep
Revision as of 21:28, 14 September 2021 by Martin (talk | contribs) (Created page with "* Containers support caching and coherence across containers, this leads to a scalable solution with little additional work * Performance problems are much reduced from the ea...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
  • Containers support caching and coherence across containers, this leads to a scalable solution with little additional work
  • Performance problems are much reduced from the early CMP
    • still need to be careful about linking objects and activating too many

Hibernate

  • Used to require a XML mapping file
  • Supports annotations much like JPA
  • Tends to have additional features and push them into the JPA
  • Supports one persistence unit per file -
  • Entity classes must be defined - no auto discovery
  • Includes Lucene search - full text
  • Indexed collections
  • Filters - similar to views but support parameters and dynamic application
  • Shorthand HQL
  • Manual flush + validator - user transactions

JPA

  • requires a persistence unit descriptor META-INF/persistence.xml
    • specifying the datasource
    • JPA specific configuration such as provider and it's options
  • one persistence unit per datasource
  • annotated classes automatically discovered
  • xml overrides annotations
  • supports multiple persistence units in persistence.xml file

Property/Field

  • public attributes are persisted using field based access i.e. direct access
  • private attributes are persisted property based access i.e. using getter methods
  • Can not mix field and property based access - can mark which by putting annotation against field or getter method
  • Getters/setters can not be final

Embeded

Object that doesn't exist on it's own outside of the object referring to it

  • can not be persisted separately

Persistence Manager Factory

  • Scans the classes for annotations
  • Creates persistence manager for managing an entity instance

Persistence Manager

  • Not thread safe - Nature of session beans this isn't a problem
    • stateful beans tied to one thread
    • stateless beans only server one thread per call => context per method
  1. manages entity - CRUD, findById, query. Manages state
    1. transient - created but not commited
    2. persisted - managed context
    3. detached - context closed or deleted
    4. removed - deleted
  2. persistence context - manage cache - queued sql, optimisations
  3. automated dirty checking - batched dirty cache flushing
  4. optimistic locking for long lived sessions
    • writes/locking delayed to the commit and locking/consistency checks performed then.
  5. can be configured to batch fetch when an iterator is accessed
  6. for a instance of the persistence manager and a persisted object multiple lookups guaranteed the same object instance
  • Allows traversing of relations - performs the lazy loading on demand
  • Caches and manages updates until flushed then cascades any changes required
  • Designed to serve a use case - stateful bean may (probably will want to) keep open across calls #Extended context
    • stateful bean configured with @PersistenceContext(type = PersistenceContextType.EXTENDED)

JDO

Java Data Objects


Entity

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class Foo implements Serializable {
@Id
private int id;

public void setId(int id) {
  this.id = id;
}

public int getId...
}
  • relationships: @OneToOne @OneToMany @ManyToMany
    • (mappedBy = "attributeName", fetch = EAGER/LAZY, optional = true/false, cascade=true/false, targetEntity=ClassRequired.clazz)
      • mappedBy when the relationship points only one way - specify owner of relationship
        • not on ManyToOne - must be owner - no mappedBy
      • optional if related object is required
        • not available on OneToMany or ManyToMany
  • mapping to tables: @Table @Column @JoinColumn
  • not persisted @Transient

http://db.apache.org/jdo/jdo_v_jpa.html

Persisted types:

  • primitive types, wrappers of primitives
  • String, BigInteger, BigDecimal, java.util.Date, java.util.Calendar
  • java.sql.Date, java.sql.Time, java.sql.Timestamp
  • anything Serializable
  • arrays (of things that can be persisted)
  • Enums
  • Collections (of things that can be persisted)

Entity Manger

  @PersistenceContext(unitName="ComponetEntityManager")
  private EntityManager em;

  em.persist(foo);


JPQL

import javax.persistence.EntityManager;

  @PersistenceContext(unitName="ComponetEntityManager")
  private EntityManager entityManager;

  Query q = entityManager.createQuery("select t from Type t where t.foo = :foo");
  q.setParameter("foo", bar);
  Type type =  (Type)q.getSingleResult( );
  • updates entityManager.flush()
    • entityManager.merge(type) issues:
      • loads another copy for comparison - extra read
      • may overwrite other changes - if detached
      • may hit non uniqueness issues and uninitialised associations

Intefaces

Much simpler than EJB 2.0 - No longer have to implement any interfaces - though some still exist - see stateful

Interface now only needs to include annotation @Remote or @Local

  • @Remote
  • remote business interface

Local/Remote interface

import javax.ejb.Remote;

@Remote
public interface FooBeanRemote {
...
}

Entity Beans

  • Just POJOs
  • Needs to implement java.io.Serializable or Externalizable to be accessed remotely
  • May throw javax.ejb.EJBException - extends java.lang.RuntimeException
  • May declare exception behaviour using @javax.ejb.ApplicationException or <application-exception>
  • May reference resources using annotations @Resource(name="xxx") rather than jndi lookup though InitialContext in code
  • Much of the deployment descriptor is now available as annotations. Deployment descriptor can still be used to argument or override
    • Note if full deployment descriptor used to define local, remote and session-type, bean could be devoid of any references to javax.ejb

Statelesss

import javax.ejb.Stateless;
@Stateless
public class FooBean implements FooBeanRemote, FooBeanLocal {
@Resource(mappedName="fooDB")
DataSource ds;
...
}

May also define local and remote interfaces with annotations This prevents compile time checking of the interfaces though

 
@Stateless
@Local(FooBeanRemote.class)
@Remote(FooBeanLocal.class)
public class FooBean  {

Stateful

  • @Remove - annotates methods - releases bean from client when called

Extended context

import static javax.persistence.PersistenceContextType.EXTENDED;
...
@PersistenceContext(unitName="ComponetEntityManager", type=EXTENDED)
private EntityManager entityManager;

... 
 public void updateFoo(String high) {
     foo.setBar(high);
 }
  • Entity manager continues to track changes to entity
  • Updates to entity automatically get commited when the method completes - no need to call merge() or flush()
  • Normal behaviour is to only track within method

Nesting

  • When one stateful bean in nested in another the create and remove are cascaded to the nested bean automatically
  • They can share the same persistence context if
    • both are local
    • both extended
    • both use the same named context

Resources

  • @Resource may also be used for any Enterprise Naming Context resource such as deployment descriptor references
<ejb-jar
       xmlns="http://java.sun.com/xml/ns/javaee"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                           http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
       version="3.0">
   <enterprise-beans>
      <session>
        <ejb-name>FooBean</ejb-name>
         <env-entry>
            <env-entry-name>bar</env-entry-name>
            <env-entry-type>java.lang.String</env-entry-type>
            <env-entry-value>ENC example</env-entry-value>
         </env-entry>
      </session>
   </enterprise-beans>
</ejb-jar>

EJB core classes

javax.ejb.SessionContext

javax.ejb.SessionContext Now accessed with

@Resource 
javax.ejb.SessionContext ctx
  • getEJBObject() and getEJBLocalObject() - now obsolete and throw an exception
  • <T> getBusinessObect(Class<T> businessInterface) - now returns the reference to current EJB to pass as a callback
    • businessInterface - must be local or remote interface
    • can not pass this reference to another bean
  • Class getInvolkedBusinessInterface() - returns local,remote or web service interface depending on which interface the current call was made

javax.ejb.EJBContext

SessionContext extends EJBContext

  • Object lookup(String name) - Convince method
  • TimerService getTimerService() - Gets a timerService to set up an event at a specific time/interval - also available as @Resource
  • java.security.Principal getCallerPrincipal() - can be used to get the name of the caller
  • UserTransaction getUserTransaction()

== javax.transaction.UserTransaction

  • void begin()
  • void commit()
  • void rollback() - when complete no transaction is associated
  • void setRollbackOnly() - marks transaction for rollback
  • void setTransactionTimeout(int seconds)
  • int getStatus()

Other technologies

Lower level: