Download - Ejb3 Presentation
Purpose
Gain better insight of EJB 3.0
Objectives
Learn about how EJB 3.0 makes development easier Learn about new entity bean development model and persistence goalsLearn about significant changes in session and message driven beans of EJB 3.0
Agenda
EJB 3.0 ApproachEntity Beans and their lifecycleEntity Manager APIEJB QLObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback
EJB 3.0 Approach
Simplification of the EJB APIsRemoval of need for EJBHomes and EJBObjectsRemoval of JNDI APIs from developer and client viewRemoval of need for deployment descriptorsAnnotations for (optional) callback methodsDependency injection, simple lookup method - No more need to use JNDI APIs
Use advantages of Java language metadataMetadata designed so that the most common cases are easiest to expressDefaults available for expected cases
More work is done by container, less by developerConfiguration by exception
EJB 3.0 Approach - Birds Eye View
The changes in the EJB 3.0 specification can be divided into two categories:
An annotation-based EJB programming model, in addition to the EJB 2.1 model of defining an application's behavior through deployment descriptors and several interfaces. The new persistence model for entity beans. EJB QL has also changed significantly.
Agenda
EJB 3.0 Approach Entity beans and their lifecycleEntity Manager APIEJB QLObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback
Entity Bean Definition
An entity is a lightweight persistent domain object.
EJB 2.1 Entity Bean Artifacts
EJB Home and EJB RemoteEJB Bean ImplementationEJB Deployment Descriptor
EJB 3.0 Entity Bean
@Entity //@Table (name="AlternativeTableName") public class Person implements Serializable { protected int id; protected String name; @Id(generate = GeneratorType.AUTO) public int getId () { return id; } public void setId (int id) { this.id = id; } // @Column (name="AlternativeColumnName") public String getName () { return name; }public void setName (String name) { this.name = name; } }
Entity Beans Lifecycle
An entity instance may be characterized as beingNew
Has no persistent identity.Not yet associated with a persistence context.
ManagedAn instance with a persistent identity that is currently associated with a persistence context.
DetachedAn instance with a persistent identity that is not (or no longer) associated with a persistence context.
RemovedInstance with a persistent identity, associated with a persistence context, that is scheduled for removal from the database.
Agenda
EJB 3.0 Approach Entity beans and their lifecycleEntity Manager APIEJB QLObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback
Entity Manager
The Entity Manager allows the application to control the life cycle of entities and execute queries
persist(), remove(), refresh() –entity bean lifecyclemerge() – synchronizes state of detached entitiesfind(), createQuery(), createNamedQuery(), createNativeQuery() queriescontains() – determines if entity is managed by persistence contextflush() – force synchronization of the persistence context with the databaseclose() – destroy the EntityManager InstancegetTransaction() – access to resource level transaction.
Persist Operations
public void createCustomer(Customer customer) {em.persist(customer);}We can only pass new or managed instance to the persistoperation. If we pass detached object an exception isthrown.
Find & Remove Operations
public void removeCustomer(Long custId) {Customer customer = em.find(Customer.class, custId);em.remove(customer);
}We can only pass managed instance to the removeoperation. If we pass new or detached object anexception is thrown.
Merge flush and refresh
public void merge(Customer customer) {customer = em.merge(Customer);em.flush();em.refresh(customer);
}Merge – If the object is detached, its state is mergedand synchronized with the DB.Flush – To force immediate synchronization with DB.Refresh – To refresh the current state from DB.
Cascading Operations
Associations may apply cascading style by choosing (multiple) options from PERSIST, REMOVE, MERGE, REFRESHThis allows us to apply an operation to a well-defined sub-graph of our object graph.
Entity Callbacks
An Entity Listener may be attached to receive defined entity lifecycle events
PrePersist() – when application calls persist()PostPersist() – after the SQL InsertPreRemove() – when application calls remove()PostRemove() – after the SQL DeletePreUpdate() – when a container detects that instance is dirtyPostUpdate() – after the SQL UpdatePostLoad() – after instance was loaded
Attached to entity class by specifying an @EntityListener annotation
The new ERA of EJB Development - EJB3.0By Saurabh Raisinghaney, March 2007
Entity Callbacks
public class AuditCallbackListener {@PrePersist public void setCreateInfo(AuditInfo audit) {
audit.setTime(new Date());audit.setUser(User.getCurrentUser());
}}
Agenda
EJB 3.0 Approach Entity beans and their lifecycleEntity Manager APIEJB QLObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback
Query API
The Query interface allows the application to control queryExecution, parameter binding and pagination.public List<Order> getOrders(Customer customer, int max) {
return em.createQuery("from Order o where o.customer = :customer").setParameter ("customer", customer).setMaxResults(max).getResultList();
}
EJB QL Enhancements
Support for joins in the from clauseSELECT o FROM Order o LEFT JOIN 0.lineItems li WHERE li.totalAmount >100
Support for subselectsSELECT o FROM Order o WHERE EXISTS (select li FROM o.lineItems WHERE li.amount > 100)
Support for dynamic association fetchingSELECT FROM Order o LEFT JOIN FETCH o.lineItems
Support for aggregationMore standard EJB-QL functions
trim(), locate(), concat(), substring() etc.Update and delete queries
DELETE FROM Order where customer.id = 12345UPDATE OrderLine SET shipping=‘Y’ where order.id= 123
Agenda
EJB 3.0 Approach Entity beans and their lifecycleEntity Manager APIEJB QLObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback
O/R Mapping
Specified as annotations or XMLSupport for basic, serialized objects and LOBsUnary and n-ary relationship mappingsRules for defaulting of DB table and column namesAccess to object state using fields or propertiesMultiple tables composite relationships
Primary Key
Id field required in the EntityCan be simplified using @Id
@Id int custId;Use @EmbeddebleId to indicate a single id field to store aninstance of a composite PK class
@EmbeddebleId CustPK custId;Table, Sequence and Identity id generation
Fetch Mode
Hint to container to defer loading specific fields or relationships of the object until they are accessed.
Defaults applied by containerSimple and single valued relationships – EAGERLobs and multi-valued relationships – LAZY
Cascade Mode
Can cause specific life cycle operations to cascade across relationshipsCan cascade combinations of
PERSISTMERGEREMOVEREFRESHALL
Default is for no cascading to occur
Simple Mapping
Relationship Mapping
Common relationship mappings@OneToOne, @ManyToOne – Single Entity@OneToMany, @ManyToMany – Collection
Unidirectional and Bi-directionalOwing side specifies the physical mapping
@JoinColumn to specify foreign key column
Mapping One to One
Mapping One to Many
Agenda
EJB 3.0 Approach Entity beans and their lifecycleEntity Manager APIEJB QLObject/Relational MappingEntity Managers & TransactionsSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback
Types of Entity Managers
Container managed entity managerLifecycle of the entity manager is controlled by Application ServerObtained through JNDI lookup or recourse injectionOpening and close handled by containerCM Entity Managers are always JTA Entity Managers
Application Managed entity managerApplication code is responsible for opening or closing entity managerDesigned to use outside j2ee containerOpening and closing handled by application code
Container Managed EM - Resource Injection
@Statelesspublic class DvdStoreBean implements DvdStore {@PersistenceContext(unitName="dvd") EntityManager em;
public Customer getCustomer(String user) {return (Customer) em.createQuery("from Customer c wherec.userName = :userName").setParameter ("userName", user).getSingleResult();}
}
Application Managed EM
public class StoreOrder {public static void main (String [] args) {
EntityManagerFactory em = emf.createEntityManager();em.getTransation().begin();em.persist(new Order(args [0]));em.getTransation().commit();em.close();
}}
Transactions
Transaction managementContainer-managed transaction (CMT) by defaultBean-managed transaction (BMT) by annotation
Container-managed transactionsREQUIRED transaction attribute by defaultAny transaction attribute by annotation
Specified at class level => applies to all business methods of the classSpecified at method level => applies to method (overriding any class-level specification)
Typical case (CMT + REQUIRED) is default
Transactions - Example
// Uses container-managed transaction, REQUIRED attribute@Stateless public class PayrollBean implements Payroll {
public void setBenefitsDeduction (int empId, double deduction) { …}public double getBenefitsDeduction(int empId) {…}public double getSalary(int empId) {…}public void setSalary(int empId, double salary) {…}…
}
Agenda
EJB 3.0 Approach Entity beans and their lifecycleEntity Manager APIEJB QLObject/Relational MappingEntity Managers & TransactionsSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback
EJB 2.1 Stateless Session Bean Artifacts
Session Bean Remote and Home InterefaceSession Bean ClassSession Bean Deployment Descriptor
EJB 3.0
@Stateless @Remotepublic class PayrollBean implements Payroll {
@Resource DataSource empDB;public void setBenefitsDeduction (int empId, double deduction) {
Connection conn = empDB.getConnection();…
}}public interface Payroll {
public void setBenefitsDeduction (int empId, double deduction);}
Agenda
Entity Beans and their lifecycleEntity Manager APIQueriesObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleSummary and Status
Message-driven Beans
Message-driven beans in EJB 3.0Bean class implements message listener interface or designates with @MessageListenerNo requirement to implement MessageDrivenBean etc.
Message-driven Beans
@MessageDriven(activateConfig = {@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"),@ActivationConfigProperty(propertyName="destination", propertyValue="jms/XXQueue"),@ActivationConfigProperty(
propertyName="connectionFactoryJndiName", propertyValue="QueueConnectionFactory")} ) public class PayMDB implements MessageListener {@Resource javax.ejb.MessageDrivenContext mc;@Resource DataSource empDB;@PersistenceContext(unitName="x") EntityManager em; public void onMessage(Message msg) { …}}
Agenda
EJB 3.0 Approach Entity Beans and their lifecycleEntity Manager APIQueriesObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback
Entity Bean Example
import javax.ejb.*;import javax.persistence.*;//Other Imports@Entity @Table(name="ORDERS")public class Order implements Serializable {Long orderId;Date orderDate;Customer customer;Float totalAmount;List<OrderLine> orderLines;@Id(generate=GeneratorType.AUTO)@Column(name="ORDERID")public long getOrderId() {return orderId;}
Entity Bean Example Cont.
public void setOrderId(long id) {this.orderId = id;}@Column(name="ORDERDATE“, nullable=false)public Date getOrderDate() {
return orderDate;}public void setOrderDate(Date date) {
this.orderDate = date;}@OneToMany(mappedBy="order", cascade=CascadeType.ALL)public List<OrderLine> getOrderLines() {
return orderLines;}public void setOrderLines(List<OrderLine> lines) {
this.orderLines = lines;}
Entity Bean Example Cont.
@ManyToOne@JoinColumn(name="CUSTOMERID")public Customer getCustomer() {
return customer;}public void setCustomer(Customer customer) {
this.customer = customer;}@Column(name="TOTALAMOUNT",nullable=false)public float getTotalAmount() {
return totalAmount;}public void setTotalAmount(float amount) {
this.totalAmount = amount;}
}
Stateless Bean
import javax.ejb.*;import javax.persistence.*;import javax.annotation.Resource;//Other imports@Stateless public class DvdStoreBean implements DvdStore {
@PersistenceContext(unitName="dvd") EntityManager em;public Customer getCustomer(String user) {
return (Customer) em.createQuery("from Customer c where c.userName = :userName").setParameter ("userName", user).getSingleResult();
}public void createCustomer(Customer customer) {
em.persist(customer);}
Stateless Bean Cont.
public Order purchase(Customer customer, List<OrderLine> lines) {Order order = new Order(); order.setCustomer(customer); order.setOrderDate(new Date());order.setOrderDate(new Date());order.setOrderLines(lines);order.setTotalAmount(order.getNetAmount() + order.getTax());em.persist(order);return order;
}}
Agenda
Entity Beans and their lifecycleEntity Manager APIQueriesObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback
EJB3.0
Feedback
PositivesDeltas