ejb3 presentation

52
Purpose Gain better insight of EJB 3.0

Upload: saurabhrais

Post on 19-May-2015

5.987 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: Ejb3 Presentation

Purpose

Gain better insight of EJB 3.0

Page 2: Ejb3 Presentation

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

Page 3: Ejb3 Presentation

Agenda

EJB 3.0 ApproachEntity Beans and their lifecycleEntity Manager APIEJB QLObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback

Page 4: Ejb3 Presentation

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

Page 5: Ejb3 Presentation

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.

Page 6: Ejb3 Presentation

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

Page 7: Ejb3 Presentation

Entity Bean Definition

An entity is a lightweight persistent domain object.

Page 8: Ejb3 Presentation

EJB 2.1 Entity Bean Artifacts

EJB Home and EJB RemoteEJB Bean ImplementationEJB Deployment Descriptor

Page 9: Ejb3 Presentation

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; } }

Page 10: Ejb3 Presentation

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.

Page 11: Ejb3 Presentation

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

Page 12: Ejb3 Presentation

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.

Page 13: Ejb3 Presentation

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.

Page 14: Ejb3 Presentation

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.

Page 15: Ejb3 Presentation

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.

Page 16: Ejb3 Presentation

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.

Page 17: Ejb3 Presentation

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

Page 18: Ejb3 Presentation

The new ERA of EJB Development - EJB3.0By Saurabh Raisinghaney, March 2007

Page 19: Ejb3 Presentation

Entity Callbacks

public class AuditCallbackListener {@PrePersist public void setCreateInfo(AuditInfo audit) {

audit.setTime(new Date());audit.setUser(User.getCurrentUser());

}}

Page 20: Ejb3 Presentation

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

Page 21: Ejb3 Presentation

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();

}

Page 22: Ejb3 Presentation

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

Page 23: Ejb3 Presentation

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

Page 24: Ejb3 Presentation

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

Page 25: Ejb3 Presentation

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

Page 26: Ejb3 Presentation

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

Page 27: Ejb3 Presentation

Cascade Mode

Can cause specific life cycle operations to cascade across relationshipsCan cascade combinations of

PERSISTMERGEREMOVEREFRESHALL

Default is for no cascading to occur

Page 28: Ejb3 Presentation

Simple Mapping

Page 29: Ejb3 Presentation

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

Page 30: Ejb3 Presentation

Mapping One to One

Page 31: Ejb3 Presentation

Mapping One to Many

Page 32: Ejb3 Presentation

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

Page 33: Ejb3 Presentation

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

Page 34: Ejb3 Presentation

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();}

}

Page 35: Ejb3 Presentation

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();

}}

Page 36: Ejb3 Presentation

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

Page 37: Ejb3 Presentation

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) {…}…

}

Page 38: Ejb3 Presentation

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

Page 39: Ejb3 Presentation

EJB 2.1 Stateless Session Bean Artifacts

Session Bean Remote and Home InterefaceSession Bean ClassSession Bean Deployment Descriptor

Page 40: Ejb3 Presentation

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);}

Page 41: Ejb3 Presentation

Agenda

Entity Beans and their lifecycleEntity Manager APIQueriesObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleSummary and Status

Page 42: Ejb3 Presentation

Message-driven Beans

Message-driven beans in EJB 3.0Bean class implements message listener interface or designates with @MessageListenerNo requirement to implement MessageDrivenBean etc.

Page 43: Ejb3 Presentation

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) { …}}

Page 44: Ejb3 Presentation

Agenda

EJB 3.0 Approach Entity Beans and their lifecycleEntity Manager APIQueriesObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback

Page 45: Ejb3 Presentation

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;}

Page 46: Ejb3 Presentation

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;}

Page 47: Ejb3 Presentation

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;}

}

Page 48: Ejb3 Presentation

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);}

Page 49: Ejb3 Presentation

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;

}}

Page 50: Ejb3 Presentation

Agenda

Entity Beans and their lifecycleEntity Manager APIQueriesObject/Relational MappingTransactions & Entity ManagersSession BeanMessage Driven BeanEntity Bean with Stateless Bean ExampleFeedback

Page 51: Ejb3 Presentation

EJB3.0

Page 52: Ejb3 Presentation

Feedback

PositivesDeltas