SlideShare a Scribd company logo
1 of 52
Download to read offline
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
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
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

More Related Content

What's hot (20)

Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
EJB 2
EJB 2EJB 2
EJB 2
 
Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJB
 
EJB 3.0 and J2EE
EJB 3.0 and J2EEEJB 3.0 and J2EE
EJB 3.0 and J2EE
 
Java EE EJB Applications
Java EE EJB ApplicationsJava EE EJB Applications
Java EE EJB Applications
 
enterprise java bean
enterprise java beanenterprise java bean
enterprise java bean
 
Ejb3.1 for the starter
Ejb3.1 for the starterEjb3.1 for the starter
Ejb3.1 for the starter
 
EJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionEJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another Introduction
 
Enterprise java beans
Enterprise java beansEnterprise java beans
Enterprise java beans
 
Session 4 Tp4
Session 4 Tp4Session 4 Tp4
Session 4 Tp4
 
EJB 3.1 by Bert Ertman
EJB 3.1 by Bert ErtmanEJB 3.1 by Bert Ertman
EJB 3.1 by Bert Ertman
 
Session bean
Session beanSession bean
Session bean
 
Ejb 2.0
Ejb 2.0Ejb 2.0
Ejb 2.0
 
Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010Contextual Dependency Injection for Apachecon 2010
Contextual Dependency Injection for Apachecon 2010
 
EJB Interview Questions
EJB Interview QuestionsEJB Interview Questions
EJB Interview Questions
 
Ejb - september 2006
Ejb  - september 2006Ejb  - september 2006
Ejb - september 2006
 
Ch4 ejb
Ch4 ejbCh4 ejb
Ch4 ejb
 
Aravind vinnakota ejb_architecture
Aravind vinnakota ejb_architectureAravind vinnakota ejb_architecture
Aravind vinnakota ejb_architecture
 
Session 3 Tp3
Session 3 Tp3Session 3 Tp3
Session 3 Tp3
 

Viewers also liked

Java EE 7: Developing for the Cloud at Geecon, JEEConf, Johannesburg
Java EE 7: Developing for the Cloud at Geecon, JEEConf, JohannesburgJava EE 7: Developing for the Cloud at Geecon, JEEConf, Johannesburg
Java EE 7: Developing for the Cloud at Geecon, JEEConf, JohannesburgArun Gupta
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5phanleson
 
JetBrains IDEハンズオン
JetBrains IDEハンズオンJetBrains IDEハンズオン
JetBrains IDEハンズオンYusuke Yamamoto
 
EJB and CDI - Alignment and Strategy
EJB and CDI - Alignment and StrategyEJB and CDI - Alignment and Strategy
EJB and CDI - Alignment and StrategyDavid Delabassee
 
JSP Scope variable And Data Sharing
JSP Scope variable And Data SharingJSP Scope variable And Data Sharing
JSP Scope variable And Data Sharingvikram singh
 
Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)Chitrank Dixit
 
Lecture 1: Introduction to JEE
Lecture 1:  Introduction to JEELecture 1:  Introduction to JEE
Lecture 1: Introduction to JEEFahad Golra
 
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...ENSET, Université Hassan II Casablanca
 

Viewers also liked (17)

Java EE 7: Developing for the Cloud at Geecon, JEEConf, Johannesburg
Java EE 7: Developing for the Cloud at Geecon, JEEConf, JohannesburgJava EE 7: Developing for the Cloud at Geecon, JEEConf, Johannesburg
Java EE 7: Developing for the Cloud at Geecon, JEEConf, Johannesburg
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
 
JetBrains IDEハンズオン
JetBrains IDEハンズオンJetBrains IDEハンズオン
JetBrains IDEハンズオン
 
EJB and CDI - Alignment and Strategy
EJB and CDI - Alignment and StrategyEJB and CDI - Alignment and Strategy
EJB and CDI - Alignment and Strategy
 
Curso Java Avanzado 5 Ejb
Curso Java Avanzado   5 EjbCurso Java Avanzado   5 Ejb
Curso Java Avanzado 5 Ejb
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
JSP Scope variable And Data Sharing
JSP Scope variable And Data SharingJSP Scope variable And Data Sharing
JSP Scope variable And Data Sharing
 
Jsp
JspJsp
Jsp
 
Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
JSP
JSPJSP
JSP
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Lecture 1: Introduction to JEE
Lecture 1:  Introduction to JEELecture 1:  Introduction to JEE
Lecture 1: Introduction to JEE
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
Frameworks J2EE
Frameworks J2EEFrameworks J2EE
Frameworks J2EE
 
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...Support de cours EJB 3 version complète Par Mr  Youssfi, ENSET, Université Ha...
Support de cours EJB 3 version complète Par Mr Youssfi, ENSET, Université Ha...
 

Similar to Ejb3 Presentation (20)

Session 6 Tp6
Session 6 Tp6Session 6 Tp6
Session 6 Tp6
 
Skillwise EJB3.0 training
Skillwise EJB3.0 trainingSkillwise EJB3.0 training
Skillwise EJB3.0 training
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
 
JavaEE Spring Seam
JavaEE Spring SeamJavaEE Spring Seam
JavaEE Spring Seam
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate
HibernateHibernate
Hibernate
 
Ecom lec4 fall16_jpa
Ecom lec4 fall16_jpaEcom lec4 fall16_jpa
Ecom lec4 fall16_jpa
 
Entity Manager
Entity ManagerEntity Manager
Entity Manager
 
Ejb6
Ejb6Ejb6
Ejb6
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
Javaee6 Overview
Javaee6 OverviewJavaee6 Overview
Javaee6 Overview
 
Jpa
JpaJpa
Jpa
 
Session 7 Tp7
Session 7 Tp7Session 7 Tp7
Session 7 Tp7
 
EJB Clients
EJB ClientsEJB Clients
EJB Clients
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
 
CommercialSystemsBahman.ppt
CommercialSystemsBahman.pptCommercialSystemsBahman.ppt
CommercialSystemsBahman.ppt
 
Ejb3 Dan Hinojosa
Ejb3 Dan HinojosaEjb3 Dan Hinojosa
Ejb3 Dan Hinojosa
 
Java EE and Glassfish
Java EE and GlassfishJava EE and Glassfish
Java EE and Glassfish
 
What's new in Java EE 6
What's new in Java EE 6What's new in Java EE 6
What's new in Java EE 6
 
J2EE - Practical Overview
J2EE - Practical OverviewJ2EE - Practical Overview
J2EE - Practical Overview
 

Recently uploaded

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESmohitsingh558521
 

Recently uploaded (20)

Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICESSALESFORCE EDUCATION CLOUD | FEXLE SERVICES
SALESFORCE EDUCATION CLOUD | FEXLE SERVICES
 

Ejb3 Presentation

  • 1. Purpose Gain better insight of EJB 3.0
  • 2. 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
  • 3. 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
  • 4. 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
  • 5. 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.
  • 6. 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
  • 7. Entity Bean Definition An entity is a lightweight persistent domain object.
  • 8. EJB 2.1 Entity Bean Artifacts EJB Home and EJB Remote EJB Bean Implementation EJB Deployment Descriptor
  • 9. 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; } }
  • 10. 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.
  • 11. 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
  • 12. 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.
  • 13. 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.
  • 14. 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.
  • 15. 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.
  • 16. 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.
  • 17. 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
  • 18. The new ERA of EJB Development - EJB3.0 By Saurabh Raisinghaney, March 2007
  • 19. Entity Callbacks public class AuditCallbackListener { @PrePersist public void setCreateInfo(AuditInfo audit) { audit.setTime(new Date()); audit.setUser(User.getCurrentUser()); } }
  • 20. 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
  • 21. 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(); }
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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
  • 29. 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
  • 32. 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
  • 33. 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
  • 34. 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(); } }
  • 35. 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(); } }
  • 36. 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
  • 37. 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) {…} … }
  • 38. 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
  • 39. EJB 2.1 Stateless Session Bean Artifacts Session Bean Remote and Home Intereface Session Bean Class Session Bean Deployment Descriptor
  • 40. 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); }
  • 41. 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
  • 42. 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.
  • 43. 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) { …} }
  • 44. 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
  • 45. 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; }
  • 46. 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; }
  • 47. 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; } }
  • 48. 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); }
  • 49. 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; } }
  • 50. 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