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
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.
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