Ejb3 Presentation
Upcoming SlideShare
Loading in...5
×
 

Ejb3 Presentation

on

  • 7,004 views

 

Statistics

Views

Total Views
7,004
Views on SlideShare
6,989
Embed Views
15

Actions

Likes
2
Downloads
243
Comments
0

3 Embeds 15

http://www.slideshare.net 11
http://www.linkedin.com 3
https://www.linkedin.com 1

Accessibility

Upload Details

Uploaded via as Adobe PDF

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

Ejb3 Presentation Ejb3 Presentation Presentation Transcript

  • 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 goals Learn about significant changes in session and message driven beans of EJB 3.0
  • Agenda EJB 3.0 Approach Entity Beans and their lifecycle Entity Manager API EJB QL Object/Relational Mapping Transactions & Entity Managers Session Bean Message Driven Bean Entity Bean with Stateless Bean Example Feedback View slide
  • EJB 3.0 Approach Simplification of the EJB APIs Removal of need for EJBHomes and EJBObjects Removal of JNDI APIs from developer and client view Removal of need for deployment descriptors Annotations for (optional) callback methods Dependency injection, simple lookup method - No more need to use JNDI APIs Use advantages of Java language metadata Metadata designed so that the most common cases are easiest to express Defaults available for expected cases More work is done by container, less by developer Configuration by exception View slide
  • 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 lifecycle Entity Manager API EJB QL Object/Relational Mapping Transactions & Entity Managers Session Bean Message Driven Bean Entity Bean with Stateless Bean Example Feedback
  • Entity Bean Definition An entity is a lightweight persistent domain object.
  • EJB 2.1 Entity Bean Artifacts EJB Home and EJB Remote EJB Bean Implementation EJB Deployment Descriptor
  • EJB 3.0 Entity Bean @Entity //@Table (name=quot;AlternativeTableNamequot;) 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=quot;AlternativeColumnNamequot;) public String getName () { return name; } public void setName (String name) { this.name = name; } }
  • Entity Beans Lifecycle An entity instance may be characterized as being New Has no persistent identity. Not yet associated with a persistence context. Managed An instance with a persistent identity that is currently associated with a persistence context. Detached An instance with a persistent identity that is not (or no longer) associated with a persistence context. Removed Instance 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 lifecycle Entity Manager API EJB QL Object/Relational Mapping Transactions & Entity Managers Session Bean Message Driven Bean Entity Bean with Stateless Bean Example Feedback
  • Entity Manager The Entity Manager allows the application to control the life cycle of entities and execute queries persist(), remove(), refresh() –entity bean lifecycle merge() – synchronizes state of detached entities find(), createQuery(), createNamedQuery(), createNativeQuery() queries contains() – determines if entity is managed by persistence context flush() – force synchronization of the persistence context with the database close() – destroy the EntityManager Instance getTransaction() – 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 persist operation. If we pass detached object an exception is thrown.
  • 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 remove operation. If we pass new or detached object an exception 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 merged and 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, REFRESH This 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 Insert PreRemove() – when application calls remove() PostRemove() – after the SQL Delete PreUpdate() – when a container detects that instance is dirty PostUpdate() – after the SQL Update PostLoad() – after instance was loaded Attached to entity class by specifying an @EntityListener annotation
  • The new ERA of EJB Development - EJB3.0 By 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 lifecycle Entity Manager API EJB QL Object/Relational Mapping Transactions & Entity Managers Session Bean Message Driven Bean Entity Bean with Stateless Bean Example Feedback
  • Query API The Query interface allows the application to control query Execution, parameter binding and pagination. public List<Order> getOrders(Customer customer, int max) { return em.createQuery(quot;from Order o where o.customer = :customerquot;) .setParameter (quot;customerquot;, customer) .setMaxResults(max) .getResultList(); }
  • EJB QL Enhancements Support for joins in the from clause SELECT o FROM Order o LEFT JOIN 0.lineItems li WHERE li. totalAmount >100 Support for subselects SELECT o FROM Order o WHERE EXISTS (select li FROM o. lineItems WHERE li.amount > 100) Support for dynamic association fetching SELECT FROM Order o LEFT JOIN FETCH o.lineItems Support for aggregation More standard EJB-QL functions trim(), locate(), concat(), substring() etc. Update and delete queries DELETE FROM Order where customer.id = 12345 UPDATE OrderLine SET shipping=‘Y’ where order.id= 123
  • Agenda EJB 3.0 Approach Entity beans and their lifecycle Entity Manager API EJB QL Object/Relational Mapping Transactions & Entity Managers Session Bean Message Driven Bean Entity Bean with Stateless Bean Example Feedback
  • O/R Mapping Specified as annotations or XML Support for basic, serialized objects and LOBs Unary and n-ary relationship mappings Rules for defaulting of DB table and column names Access to object state using fields or properties Multiple tables composite relationships
  • Primary Key Id field required in the Entity Can be simplified using @Id @Id int custId; Use @EmbeddebleId to indicate a single id field to store an instance 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 container Simple and single valued relationships – EAGER Lobs and multi-valued relationships – LAZY
  • Cascade Mode Can cause specific life cycle operations to cascade across relationships Can cascade combinations of PERSIST MERGE REMOVE REFRESH ALL Default is for no cascading to occur
  • Simple Mapping
  • Relationship Mapping Common relationship mappings @OneToOne, @ManyToOne – Single Entity @OneToMany, @ManyToMany – Collection Unidirectional and Bi-directional Owing 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 lifecycle Entity Manager API EJB QL Object/Relational Mapping Entity Managers & Transactions Session Bean Message Driven Bean Entity Bean with Stateless Bean Example Feedback
  • Types of Entity Managers Container managed entity manager Lifecycle of the entity manager is controlled by Application Server Obtained through JNDI lookup or recourse injection Opening and close handled by container CM Entity Managers are always JTA Entity Managers Application Managed entity manager Application code is responsible for opening or closing entity manager Designed to use outside j2ee container Opening and closing handled by application code
  • Container Managed EM - Resource Injection @Stateless public class DvdStoreBean implements DvdStore { @PersistenceContext(unitName=quot;dvdquot;) EntityManager em; public Customer getCustomer(String user) { return (Customer) em .createQuery(quot;from Customer c where c.userName = :userNamequot;) .setParameter (quot;userNamequot;, 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 management Container-managed transaction (CMT) by default Bean-managed transaction (BMT) by annotation Container-managed transactions REQUIRED transaction attribute by default Any transaction attribute by annotation Specified at class level => applies to all business methods of the class Specified 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 lifecycle Entity Manager API EJB QL Object/Relational Mapping Entity Managers & Transactions Session Bean Message Driven Bean Entity Bean with Stateless Bean Example Feedback
  • EJB 2.1 Stateless Session Bean Artifacts Session Bean Remote and Home Intereface Session Bean Class Session Bean Deployment Descriptor
  • EJB 3.0 @Stateless @Remote public 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 lifecycle Entity Manager API Queries Object/Relational Mapping Transactions & Entity Managers Session Bean Message Driven Bean Entity Bean with Stateless Bean Example Summary and Status
  • Message-driven Beans Message-driven beans in EJB 3.0 Bean class implements message listener interface or designates with @MessageListener No requirement to implement MessageDrivenBean etc.
  • Message-driven Beans @MessageDriven(activateConfig = { @ActivationConfigProperty( propertyName=quot;destinationTypequot;, propertyValue=quot;javax.jms.Queuequot;), @ActivationConfigProperty( propertyName=quot;destinationquot;, propertyValue=quot;jms/XXQueuequot;), @ActivationConfigProperty( propertyName=quot;connectionFactoryJndiNamequot;, propertyValue=quot; QueueConnectionFactoryquot;) }) public class PayMDB implements MessageListener { @Resource javax.ejb.MessageDrivenContext mc; @Resource DataSource empDB; @PersistenceContext(unitName=quot;xquot;) EntityManager em; public void onMessage(Message msg) { …} }
  • Agenda EJB 3.0 Approach Entity Beans and their lifecycle Entity Manager API Queries Object/Relational Mapping Transactions & Entity Managers Session Bean Message Driven Bean Entity Bean with Stateless Bean Example Feedback
  • Entity Bean Example import javax.ejb.*; import javax.persistence.*; //Other Imports @Entity @Table(name=quot;ORDERSquot;) public class Order implements Serializable { Long orderId; Date orderDate; Customer customer; Float totalAmount; List<OrderLine> orderLines; @Id(generate=GeneratorType.AUTO) @Column(name=quot;ORDERIDquot;) public long getOrderId() { return orderId; }
  • Entity Bean Example Cont. public void setOrderId(long id) { this.orderId = id; } @Column(name=quot;ORDERDATE“, nullable=false) public Date getOrderDate() { return orderDate; } public void setOrderDate(Date date) { this.orderDate = date; } @OneToMany(mappedBy=quot;orderquot;, 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=quot;CUSTOMERIDquot;) public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; } @Column(name=quot;TOTALAMOUNTquot;,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=quot;dvdquot;) EntityManager em; public Customer getCustomer(String user) { return (Customer) em.createQuery(quot;from Customer c where c. userName = :userNamequot;) .setParameter (quot;userNamequot;, 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 lifecycle Entity Manager API Queries Object/Relational Mapping Transactions & Entity Managers Session Bean Message Driven Bean Entity Bean with Stateless Bean Example Feedback
  • EJB3.0
  • Feedback Positives Deltas