SlideShare une entreprise Scribd logo
1  sur  42
An Overview of Enterprise Bean World
The EJB component are server-side components
that encapsulate application behavior such as
business logic and persistence code.
There are three types of EJB components: session
beans, message-driven beans, and entities.
Session beans and message-driven beans are used
to implement business logic in an EJB
application, while entities are used for persistence.
EJB components reside inside the EJB container.
Together, the components, or EJBs, and the
container can be viewed as a framework providing
services.
Metadata annotations are used to preconfigure
the EJBs by specifying the type of services to
add when the container deploys the EJBs.
Annotations are used to specify the type of the
EJB component and to specify the services.
In a layered architecture, components are
grouped into tiers.
Each tier in the application has a well-defined
purpose.
Each layer delegates the work to a layer
underneath it.
EJB allows to build applications using two
different layered architectures: the traditional
four-tier architecture and domain-driven design
(DDD).
The presentation layer is responsible for rendering the
graphical user interface (GUI) and handling user input.
The presentation layer passes down each request for
application functionality to the business logic layer.
The business logic layer is the heart of the application and
contains workflow and processing logic.
It models the distinct actions or processes the application
performs.
The business logic layer retrieves data from and saves data
into the database by utilizing the persistence tier.
The persistence layer provides a high-level object-oriented
(OO) abstraction over the database layer which typically
consists of a relational database management system
(RDBMS).
EJB provides support for implementing the business
logic and persistence layers.
Session beans and message-driven beans (MDBs)
reside in and use the services in the business logic tier
while entities reside in and use services in the
persistence tier.
The traditional architecture undermines the OO ideal
of modeling the business domain as objects that
encapsulate both data and behavior.
It focuses on modeling business processes instead of
the domain tending the business logic to look more
like a database-driven procedural application than an
OO one.
DDD emphasizes that domain objects should
contain business logic and should not just be a
dumb replica of database records.
The domain objects are known as entities in
EJB 3.
The entities defined by EJB 3 Java Persistence
API (JPA) support OO features, such as
inheritance or polymorphism.
Entities are used to model domain objects,
including modeling state and behavior.
Ease of use: It doesn’t demand that to
understand the theoretical intricacies.
Integrated solution stack: It offers seamless
integration with other J2ee technolgies and a
complete stack of server solutions, including
persistence, messaging, lightweight scheduling,
remoting, web services, dependency injection
(DI), and interceptors.
Open Java EE standard: EJB 3 has an open,
public API specification and is developed by the
Java Community Process (JCP).
Broad vendor support: EJB is supported by a
large and diverse variety of independent
organizations.
Stable, high-quality code base: a relatively
stable code base that has lived through some of
the most demanding enterprise environments.
Clustering, load balancing, and failover: EJB
application servers have a proven track record
of supporting some of the largest high-
performance computing environments.
Each bean type serves a purpose and can use a
specific subset of EJB services.
The purpose of bean types is to safeguard against
overloading them with services that cross wires.
Session beans and message-driven beans (MDBs) live
and managed by the container, and are used to build
business logic.
Entities are used to model the persistence part of an
application and persistence provider manages entities.
A persistence provider is pluggable within the
container and is abstracted behind the Java
Persistence API (JPA).
A session bean is invoked by a client to perform a specific
business operation.
A session bean instance is available only for the duration of a
“unit of work” and does not survive a server crash or
shutdown.
There are two types of session beans: stateful and stateless.
A stateful session bean automatically saves bean state between
client invocations.
A stateless session bean does not maintain any state and
models the application services that can be completed in a
single client invocation.
A session bean can be invoked either locally or remotely using
Java RMI.
A stateless session bean can be exposed as a web service.
MDBs process the business logic.
Clients never invoke MDB methods directly.
MDBs are triggered by messages sent to a
messaging server, which enables sending
asynchronous messages between system
components.
MDBs are typically used for robust system
integration or asynchronous processing.
Entities are the Java objects that are persisted
into the database.
Entities model lower-level application concepts
that high-level business processes manipulate.
Entities are OO representations of the
application data stored in the database and
hence survives container crashes and shutdown.
JPA entities support OO capabilities, including
relationships between entities, inheritance, and
polymorphism.
The JPA EntityManager interface manages entities in
terms of actually providing persistence services.
The EntityManager interface reads the ORM metadata for
an entity and performs persistence operations.
The EntityManager knows how to add entities to the
database, update stored entities, and delete and retrieve
entities from the database.
JPA provides the ability to handle lifecycle management,
performance tuning, caching, and transaction
management.
JPA provides a specialized SQL-like query language called
the Java Persistence Query Language (JPQL) to search for
entities saved into the database.
The EJB container: The EJB container transparently
provides EJB component services such as
transactions, security management, remoting, and
web services support.
In EJB 3, the container provides services applicable to
session beans and MDBs only.
The persistence provider: JPA provides persistence
services such as retrieving, adding, modifying, and
deleting JPA entities when you explicitly ask for them
by invoking EntityManager API methods.
Service Applies To
Integration Session beans and MDBs
Pooling Stateless session beans, MDBs
Thread-safety Session beans and MDBs
State management Stateful session beans
Messaging MDBs
Transactions Session beans and MDB
Security Session beans
Interceptors Session beans and MDBs
Remote access Session beans
Web services Stateless session beans
Persistence Entities
Caching and Performance Entities
package ejb3inaction.example;
public interface HelloUser {
public void sayHello(String name);
}
package ejb3inaction.example;
import javax.ejb.Stateless;
@Stateless
public class HelloUserBean implements HelloUser {
public void sayHello(String name) {
System.out.println("Hello " + name + " welcome to EJB
3!");
}
}
Simplified programming model: EJB 3 enables to develop
an EJB component using POJOs and POJIs that know
nothing about platform services.
Annotations instead of deployment descriptors: EJB 3
allows us to use metadata annotations to configure a
component instead of using XML deployment descriptors
Dependency injection vs. JNDI lookup: JNDI lookups have
been turned into simple configuration using metadata-
based dependency injection (DI). E.g. @EJB annotation
injects EJB into the annotated variable.
Unit-testable POJO components: EJB 3 components are
POJOs, and can be easily be executed outside the
container using testing frameworks such as JUnit or
TestNG.
EJB 3 manipulates metadata-based POJOs through the
EntityManager interface and avoids carrying burden of
remote access.
Standardized persistence: EJB 3 solidifies automated
persistence with JPA providing robust ORM
configuration, JPQL standardizing divergent OR query
technologies and EntityManager API standardizing
ORM CRUD operations.
The cleanly separated Java Persistence API: JPA a
cleanly separated API running outside EJB container.
Better persistence-tier OO support: EJB 3 entities have
robust OO support as they are POJOs and JPA ORM
mapping scheme is designed with OO, JPQL supporting
OO as well.
Annotations “attach” additional information
(attributes) to a Java class, interface, method, or
variable.
An annotation is a special kind of interface, it must be
imported from where it is defined.
EJB 3 allows to override annotations with XML
deployment descriptors where appropriate.
A deployment descriptor is simply an XML file that
contains application configuration information.
Deployment descriptor entries override configuration
values hard-coded using annotations into EJB
components.
Annotations Usage Use
javax.annotation.Resource Dependency injection of resources EJB, web,
app client
javax.ejb.EJB Dependency injection of session
beans
EJB, web,
app client
javax.jws.WebServiceRef Dependency injection of web
services
EJB, web,
app client
javax.persistence.PersistenceContext Dependency injection of
container-managed EntityManager
EJB, web
javax.persistence.PersistenceUnit Dependency injection of
EntityManagerFactory
EJB, web
javax.annotation.PostConstruct Lifecycle method EJB, web
javax.annotation.PreDestroy Lifecycle method EJB, web
javax.annotation.security.RunAs Security EJB, web
javax.annotation.security.RolesAllowed Security EJB
javax.annotation.security.PermitAll Security EJB
javax.annotation.security.DenyAll Security EJB
javax.annotation.security.DeclareRoles Security EJB, web
Goal of dependency injection (DI) is to make component
interdependencies as loosely coupled as possible.
One component calls another component or resource only
through an interface.
The DI is JNDI lookup model reversed.
In previous JNDI lookup model, the bean explicitly retrieves
the resources and components which are hard-coded in the
bean.
In DI, the container reads the target bean configuration and
gets the beans and resources needed by bean and injects
them into the bean at runtime.
It lets the container deal with the complexities of service
or resource instantiation, initialization, sequencing, and
supplies the service or resource references to the clients as
required.
Stateless session beans are used to model actions or
processes that can be done in one shot.
@Stateless—The @Stateless annotation tells the EJB
container that declared Bean is a stateless session bean.
The container automatically provides such services to
the bean as automatic concurrency control, thread
safety, pooling, and transaction management.
@Local—The @Local annotation on the interface tells
the container that the implementing EJB can be
accessed locally through the interface. Alternatively,
when marked with @Remote annotation, remote access
through the @Remote annotation is provided under the
hood by Java Remote Method Invocation (RMI).
import javax.ejb.Stateless;
import ejb3inaction.example.persistence.Bid;
@Stateless
public class PlaceBidBean implements PlaceBid {
public PlaceBidBean() {}
public Bid addBid(Bid bid) {
System.out.println("Adding bid, bidder ID=" + bid.getBidderID()
+ ", item ID=" + bid.getItemID() + ", bid amount="
+ bid.getBidAmount() + ".");
return save(bid);
} ….
}
...
import javax.ejb.Local;
import ejb3inaction.example.persistence.Bid;
@Local
public interface PlaceBid { Bid addBid(Bid bid); }
public class PlaceBidServlet extends HttpServlet {
@EJB
private PlaceBid placeBid;
public void service(….) {
Bid bid = new Bid();
bid.setBidderID(bidderID); ……..
placeBid.addBid(bid);
}
}
When the servlet container sees the @EJB annotation as servlet
is first loaded, it looks up the PlaceBid EJB behind the scenes
and sets the placeBid variable to the retrieved EJB reference.
If necessary, the container will look up the EJB remotely over
RMI by running the client in the application client container.
The application client container is a mini Java EE container that
can be run from the command line
The @EJB annotation makes the container
“instantiate” the placeBid variable with the EJB named
PlaceBid before the variable is available for use.
JNDI is the container registry that holds references to
all container-managed resources such as EJBs.
Clients gain access to session beans like the PlaceBid
EJB directly or indirectly through JNDI as follows:
Object ejbHome = new
InitialContext().lookup("java:comp/env/PlaceBid");
PlaceBidHome placeBidHome = (PlaceBidHome)
PortableRemoteObject.narrow(ejbHome, PlaceBidHome.class);
PlaceBid placeBid = placeBidHome.create();
Stateful session beans guarantee that a client can
expect to set the internal state of a bean and count on
the state being maintained between any number of
method calls.
The container ensures that a client can reach a bean
dedicated to it across more than one method
invocation.
The container ensures that bean instance variable
values are maintained for the duration of a session
without your having to write any session maintenance
code.
In a stateful bean, the data the user enters at each step
can be cached into bean variables until the workflow
completes.
import javax.ejb.*;
@Stateful
public class PlaceOrderBean implements PlaceOrder {
private Long bidderID;
private List<Long> items;
private ShippingInfo shippingInfo;
private BillingInfo billingInfo;
public PlaceOrderBean () { items = new ArrayList<Long>(); }
public void setBidderID(Long bidderId) { this.bidderId = bidderId; }
public void addItem(Long itemId) { items.add(itemId); }
…..
@Remove
public Long confirmOrder() {
Order order = new Order(); order.setBidderId(bidderId);
order.setItems(items); order.setShippingInfo(shippingInfo);
order.setBillingInfo(billingInfo); saveOrder(order);
billOrder(order); return order.getOrderId();
}
The @Remove annotation marks the end of the
workflow modeled by a stateful bean.
The container is told that there is no longer a need
to maintain the bean’s session with the client after
the confirmOrder method is invoked.
If the container is never told what method
invocation marks the end of the workflow, the
container could wait for a long time until it could
safely time-out the session.
Since stateful beans are guaranteed to be
dedicated to a client for the duration of a session, a
lot of “orphaned” state data is consuming the
precious server resources for long periods of time.
@Stateful
public class PlaceOrderBean implements PlaceOrder {
@Resource(name="jms/QueueConnectionFactory")
private ConnectionFactory connectionFactory;
@Resource(name="jms/OrderBillingQueue")
private Destination billingQueue;
@Remove
public Long confirmOrder() {
Order order = new Order();
order.setBidderId(bidderId);
order.setItems(items);
saveOrder(order);
billOrder(order);
return order.getOrderId();
}
private billOrder(Order order) {
try {
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
MessageProducer producer =
session.createProducer(billingQueue);
ObjectMessage message = session.createObjectMessage();
message.setObject(order);
producer.send(message);
producer.close();
session.close();
connection.close();
} catch(Exception e){ e.printStackTrace(); }
The @Resource annotation is much more
general purpose and can be used to inject
anything that the container knows about.
The name parameter values specify what
resources are bound to the EJB’s environment
naming context.
@MessageDriven( activationConfig = {
@ActivationConfigProperty(
propertyName="destinationName",
propertyValue="jms/OrderBillingQueue") } )
public class OrderBillingMDB implements MessageListener {
public void onMessage(Message message) {
try {
ObjectMessage objectMessage = (ObjectMessage) message;
Order order = (Order) objectMessage.getObject();
try {
bill(order); notifyBillingSuccess(order);
order.setStatus(OrderStatus.COMPLETE);
} catch (BillingException be) {
notifyBillingFailure(be, order);
order.setStatus(OrderStatus.BILLING_FAILED);
} finally { update(order); }
} catch (Exception e) { e.printStackTrace(); }
}
MDBs are not guaranteed to maintain state.
The @MessageDriven annotation makes the container
transparently provide messaging and other EJB
services into a POJO.
The activation configuration properties nested inside
the @MessageDriven annotation informs MDB about
the JMS destination to receive messages.
MDBs implement the javax.jms.MessageListener
interface which is used by container to invoke the
MDB.
The onMessage method defined by the interface has a
single javax.jms.Message parameter that the container
uses to pass(forward) a received message to the MDB.
The JPA EntityManager interface defines the API for persistence
while JPA entities specify how application data is mapped to a
relational database.
The @Entity annotation signifies the fact that the Class is a JPA
entity.
The @Table annotation tells JPA that the JPA entity is mapped to
the corresponding SQL table
The @Column annotations indicate which Entity properties map
to which SQL table fields.
The field mappings could have been placed directly onto
member variables exposed through nonprivate access
modifiers.
The @Id annotation marks the corresponding property as the
primary key for the Bid entity.
The @GeneratedValue allows to automatically generate the
primary key when the entity is saved into the database.
@Entity
@Table(name="BIDS")
public class Bid implements Serializable {
private Long bidID;
private Long itemID;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="BID_ID")
public Long getBidID() { return bidID; }
public void setBidID(Long bidID) { this.bidID = bidID; }
@Column(name="ITEM_ID")
public Long getItemID() { return itemID; }
public void setItemID(Long itemID) { this.itemID = itemID; }
The JPA EntityManager performs saving of the entity
into the database by reading ORM configuration and
providing entity persistence services through an API-
based interface.
The manager reads the ORM mapping annotations like
@Table and @Column on the entity and figures out how
to save the entity into the database.
The EntityManager is injected into the PlaceBid bean
through the @PersistenceContext annotation.
The unitName parameter of the @PersistenceContext
annotation points to the persistence unit of application.
A persistence unit is a group of entities packaged
together in an application module.
The save method of EntityManager presists the data
into the database issuing an SQL statement to insert a
record in DB.
public class PlaceBidBean implements PlaceBid {
@PersistenceContext(unitName="actionBazaar")
private EntityManager entityManager;
…..
private Bid save(Bid bid) {
entityManager.persist(bid);
return bid;
}
}

Contenu connexe

Tendances

Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
Guo Albert
 

Tendances (20)

JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
 
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
MySQL Tutorial For Beginners | Relational Database Management System | MySQL ...
 
LINQ in C#
LINQ in C#LINQ in C#
LINQ in C#
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface) Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface)
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controls
 
Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Recycler view
Recycler viewRecycler view
Recycler view
 
Restful web services ppt
Restful web services pptRestful web services ppt
Restful web services ppt
 
Proxy Design Patterns
Proxy Design PatternsProxy Design Patterns
Proxy Design Patterns
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Introduction to Eclipse IDE
Introduction to Eclipse IDEIntroduction to Eclipse IDE
Introduction to Eclipse IDE
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
Json
JsonJson
Json
 
Jdbc
JdbcJdbc
Jdbc
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
JMS-Java Message Service
JMS-Java Message ServiceJMS-Java Message Service
JMS-Java Message Service
 
Ajax
AjaxAjax
Ajax
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
MVC Framework
MVC FrameworkMVC Framework
MVC Framework
 

En vedette

Ejb 2.0
Ejb 2.0Ejb 2.0
Ejb 2.0
sukace
 
Object and component based middleware for distributed system development
Object and component based middleware for distributed system developmentObject and component based middleware for distributed system development
Object and component based middleware for distributed system development
ektabhalwara
 
Session 7 Tp7
Session 7 Tp7Session 7 Tp7
Session 7 Tp7
phanleson
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
phanleson
 

En vedette (20)

Enterprise Java Beans - EJB
Enterprise Java Beans - EJBEnterprise Java Beans - EJB
Enterprise Java Beans - EJB
 
EJB .
EJB .EJB .
EJB .
 
Lecture 8 Enterprise Java Beans (EJB)
Lecture 8  Enterprise Java Beans (EJB)Lecture 8  Enterprise Java Beans (EJB)
Lecture 8 Enterprise Java Beans (EJB)
 
Java bean
Java beanJava bean
Java bean
 
Entity beans in java
Entity beans in javaEntity beans in java
Entity beans in java
 
EJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another IntroductionEJB 3.0 - Yet Another Introduction
EJB 3.0 - Yet Another Introduction
 
Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)
 
Ejb3 Presentation
Ejb3 PresentationEjb3 Presentation
Ejb3 Presentation
 
EJB 2
EJB 2EJB 2
EJB 2
 
Enterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business LogicEnterprise Java Beans 3 - Business Logic
Enterprise Java Beans 3 - Business Logic
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Entreprise Java Beans (EJB)
Entreprise Java Beans (EJB)Entreprise Java Beans (EJB)
Entreprise Java Beans (EJB)
 
Ejb 2.0
Ejb 2.0Ejb 2.0
Ejb 2.0
 
Implicit Middleware
Implicit MiddlewareImplicit Middleware
Implicit Middleware
 
Couchbase - Yet Another Introduction
Couchbase - Yet Another IntroductionCouchbase - Yet Another Introduction
Couchbase - Yet Another Introduction
 
Object and component based middleware for distributed system development
Object and component based middleware for distributed system developmentObject and component based middleware for distributed system development
Object and component based middleware for distributed system development
 
Ejb notes
Ejb notesEjb notes
Ejb notes
 
Session 7 Tp7
Session 7 Tp7Session 7 Tp7
Session 7 Tp7
 
Session 5 Tp5
Session 5 Tp5Session 5 Tp5
Session 5 Tp5
 
Database Access With JDBC
Database Access With JDBCDatabase Access With JDBC
Database Access With JDBC
 

Similaire à EJB3 Basics

J2EE Notes JDBC database Connectiviy and Programs related to JDBC
J2EE Notes JDBC database Connectiviy and Programs related to JDBCJ2EE Notes JDBC database Connectiviy and Programs related to JDBC
J2EE Notes JDBC database Connectiviy and Programs related to JDBC
ChaithraCSHirematt
 
Ejb - september 2006
Ejb  - september 2006Ejb  - september 2006
Ejb - september 2006
achraf_ing
 
Topic4 Application Servers
Topic4 Application ServersTopic4 Application Servers
Topic4 Application Servers
sanjoysanyal
 
Session 2 Tp2
Session 2 Tp2Session 2 Tp2
Session 2 Tp2
phanleson
 

Similaire à EJB3 Basics (20)

Enterprise java beans
Enterprise java beansEnterprise java beans
Enterprise java beans
 
Aravind vinnakota ejb_architecture
Aravind vinnakota ejb_architectureAravind vinnakota ejb_architecture
Aravind vinnakota ejb_architecture
 
Ejb intro
Ejb introEjb intro
Ejb intro
 
Introcution to EJB
Introcution to EJBIntrocution to EJB
Introcution to EJB
 
Introduction to ejb and struts framework
Introduction to ejb and struts frameworkIntroduction to ejb and struts framework
Introduction to ejb and struts framework
 
ADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.pptADVANCED JAVA MODULE I & II.ppt
ADVANCED JAVA MODULE I & II.ppt
 
EJB.docx
EJB.docxEJB.docx
EJB.docx
 
Unite5-EJB-2019.ppt
Unite5-EJB-2019.pptUnite5-EJB-2019.ppt
Unite5-EJB-2019.ppt
 
Ejb intro
Ejb introEjb intro
Ejb intro
 
J2EE Notes JDBC database Connectiviy and Programs related to JDBC
J2EE Notes JDBC database Connectiviy and Programs related to JDBCJ2EE Notes JDBC database Connectiviy and Programs related to JDBC
J2EE Notes JDBC database Connectiviy and Programs related to JDBC
 
Ejb - september 2006
Ejb  - september 2006Ejb  - september 2006
Ejb - september 2006
 
Java J2EE
Java J2EEJava J2EE
Java J2EE
 
B Shilpa
B ShilpaB Shilpa
B Shilpa
 
Ch4 ejb
Ch4 ejbCh4 ejb
Ch4 ejb
 
Topic4 Application Servers
Topic4 Application ServersTopic4 Application Servers
Topic4 Application Servers
 
Jsf
JsfJsf
Jsf
 
A dynamic application using jboss
A dynamic application using jbossA dynamic application using jboss
A dynamic application using jboss
 
Session 2 Tp2
Session 2 Tp2Session 2 Tp2
Session 2 Tp2
 
J2EE PPT --CINTHIYA.M Krishnammal college for women
J2EE PPT --CINTHIYA.M Krishnammal college for womenJ2EE PPT --CINTHIYA.M Krishnammal college for women
J2EE PPT --CINTHIYA.M Krishnammal college for women
 
J2EE Architecture Explained
J2EE  Architecture ExplainedJ2EE  Architecture Explained
J2EE Architecture Explained
 

Plus de Emprovise

Plus de Emprovise (20)

Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
Highlights of AWS ReInvent 2023 (Announcements and Best Practices)
 
Leadership and Success Lessons for Life/Business
Leadership and Success Lessons for Life/BusinessLeadership and Success Lessons for Life/Business
Leadership and Success Lessons for Life/Business
 
Secure socket layer
Secure socket layerSecure socket layer
Secure socket layer
 
Effective java
Effective javaEffective java
Effective java
 
EJB3 Advance Features
EJB3 Advance FeaturesEJB3 Advance Features
EJB3 Advance Features
 
RESTful WebServices
RESTful WebServicesRESTful WebServices
RESTful WebServices
 
J2EE Patterns
J2EE PatternsJ2EE Patterns
J2EE Patterns
 
Spring JMS
Spring JMSSpring JMS
Spring JMS
 
JMS
JMSJMS
JMS
 
Spring Web Services
Spring Web ServicesSpring Web Services
Spring Web Services
 
Spring Web Webflow
Spring Web WebflowSpring Web Webflow
Spring Web Webflow
 
Spring Web Views
Spring Web ViewsSpring Web Views
Spring Web Views
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Enterprise Spring
Enterprise SpringEnterprise Spring
Enterprise Spring
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Apache Struts 2 Advance
Apache Struts 2 AdvanceApache Struts 2 Advance
Apache Struts 2 Advance
 
Apache Struts 2 Framework
Apache Struts 2 FrameworkApache Struts 2 Framework
Apache Struts 2 Framework
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Advance Concepts
Java Advance ConceptsJava Advance Concepts
Java Advance Concepts
 
Java Basics
Java BasicsJava Basics
Java Basics
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 

EJB3 Basics

  • 1. An Overview of Enterprise Bean World
  • 2. The EJB component are server-side components that encapsulate application behavior such as business logic and persistence code. There are three types of EJB components: session beans, message-driven beans, and entities. Session beans and message-driven beans are used to implement business logic in an EJB application, while entities are used for persistence. EJB components reside inside the EJB container. Together, the components, or EJBs, and the container can be viewed as a framework providing services.
  • 3. Metadata annotations are used to preconfigure the EJBs by specifying the type of services to add when the container deploys the EJBs. Annotations are used to specify the type of the EJB component and to specify the services.
  • 4. In a layered architecture, components are grouped into tiers. Each tier in the application has a well-defined purpose. Each layer delegates the work to a layer underneath it. EJB allows to build applications using two different layered architectures: the traditional four-tier architecture and domain-driven design (DDD).
  • 5.
  • 6. The presentation layer is responsible for rendering the graphical user interface (GUI) and handling user input. The presentation layer passes down each request for application functionality to the business logic layer. The business logic layer is the heart of the application and contains workflow and processing logic. It models the distinct actions or processes the application performs. The business logic layer retrieves data from and saves data into the database by utilizing the persistence tier. The persistence layer provides a high-level object-oriented (OO) abstraction over the database layer which typically consists of a relational database management system (RDBMS).
  • 7. EJB provides support for implementing the business logic and persistence layers. Session beans and message-driven beans (MDBs) reside in and use the services in the business logic tier while entities reside in and use services in the persistence tier. The traditional architecture undermines the OO ideal of modeling the business domain as objects that encapsulate both data and behavior. It focuses on modeling business processes instead of the domain tending the business logic to look more like a database-driven procedural application than an OO one.
  • 8. DDD emphasizes that domain objects should contain business logic and should not just be a dumb replica of database records. The domain objects are known as entities in EJB 3. The entities defined by EJB 3 Java Persistence API (JPA) support OO features, such as inheritance or polymorphism. Entities are used to model domain objects, including modeling state and behavior.
  • 9. Ease of use: It doesn’t demand that to understand the theoretical intricacies. Integrated solution stack: It offers seamless integration with other J2ee technolgies and a complete stack of server solutions, including persistence, messaging, lightweight scheduling, remoting, web services, dependency injection (DI), and interceptors. Open Java EE standard: EJB 3 has an open, public API specification and is developed by the Java Community Process (JCP).
  • 10. Broad vendor support: EJB is supported by a large and diverse variety of independent organizations. Stable, high-quality code base: a relatively stable code base that has lived through some of the most demanding enterprise environments. Clustering, load balancing, and failover: EJB application servers have a proven track record of supporting some of the largest high- performance computing environments.
  • 11. Each bean type serves a purpose and can use a specific subset of EJB services. The purpose of bean types is to safeguard against overloading them with services that cross wires. Session beans and message-driven beans (MDBs) live and managed by the container, and are used to build business logic. Entities are used to model the persistence part of an application and persistence provider manages entities. A persistence provider is pluggable within the container and is abstracted behind the Java Persistence API (JPA).
  • 12.
  • 13. A session bean is invoked by a client to perform a specific business operation. A session bean instance is available only for the duration of a “unit of work” and does not survive a server crash or shutdown. There are two types of session beans: stateful and stateless. A stateful session bean automatically saves bean state between client invocations. A stateless session bean does not maintain any state and models the application services that can be completed in a single client invocation. A session bean can be invoked either locally or remotely using Java RMI. A stateless session bean can be exposed as a web service.
  • 14. MDBs process the business logic. Clients never invoke MDB methods directly. MDBs are triggered by messages sent to a messaging server, which enables sending asynchronous messages between system components. MDBs are typically used for robust system integration or asynchronous processing.
  • 15. Entities are the Java objects that are persisted into the database. Entities model lower-level application concepts that high-level business processes manipulate. Entities are OO representations of the application data stored in the database and hence survives container crashes and shutdown. JPA entities support OO capabilities, including relationships between entities, inheritance, and polymorphism.
  • 16. The JPA EntityManager interface manages entities in terms of actually providing persistence services. The EntityManager interface reads the ORM metadata for an entity and performs persistence operations. The EntityManager knows how to add entities to the database, update stored entities, and delete and retrieve entities from the database. JPA provides the ability to handle lifecycle management, performance tuning, caching, and transaction management. JPA provides a specialized SQL-like query language called the Java Persistence Query Language (JPQL) to search for entities saved into the database.
  • 17.
  • 18. The EJB container: The EJB container transparently provides EJB component services such as transactions, security management, remoting, and web services support. In EJB 3, the container provides services applicable to session beans and MDBs only. The persistence provider: JPA provides persistence services such as retrieving, adding, modifying, and deleting JPA entities when you explicitly ask for them by invoking EntityManager API methods.
  • 19. Service Applies To Integration Session beans and MDBs Pooling Stateless session beans, MDBs Thread-safety Session beans and MDBs State management Stateful session beans Messaging MDBs Transactions Session beans and MDB Security Session beans Interceptors Session beans and MDBs Remote access Session beans Web services Stateless session beans Persistence Entities Caching and Performance Entities
  • 20. package ejb3inaction.example; public interface HelloUser { public void sayHello(String name); } package ejb3inaction.example; import javax.ejb.Stateless; @Stateless public class HelloUserBean implements HelloUser { public void sayHello(String name) { System.out.println("Hello " + name + " welcome to EJB 3!"); } }
  • 21. Simplified programming model: EJB 3 enables to develop an EJB component using POJOs and POJIs that know nothing about platform services. Annotations instead of deployment descriptors: EJB 3 allows us to use metadata annotations to configure a component instead of using XML deployment descriptors Dependency injection vs. JNDI lookup: JNDI lookups have been turned into simple configuration using metadata- based dependency injection (DI). E.g. @EJB annotation injects EJB into the annotated variable. Unit-testable POJO components: EJB 3 components are POJOs, and can be easily be executed outside the container using testing frameworks such as JUnit or TestNG.
  • 22. EJB 3 manipulates metadata-based POJOs through the EntityManager interface and avoids carrying burden of remote access. Standardized persistence: EJB 3 solidifies automated persistence with JPA providing robust ORM configuration, JPQL standardizing divergent OR query technologies and EntityManager API standardizing ORM CRUD operations. The cleanly separated Java Persistence API: JPA a cleanly separated API running outside EJB container. Better persistence-tier OO support: EJB 3 entities have robust OO support as they are POJOs and JPA ORM mapping scheme is designed with OO, JPQL supporting OO as well.
  • 23. Annotations “attach” additional information (attributes) to a Java class, interface, method, or variable. An annotation is a special kind of interface, it must be imported from where it is defined. EJB 3 allows to override annotations with XML deployment descriptors where appropriate. A deployment descriptor is simply an XML file that contains application configuration information. Deployment descriptor entries override configuration values hard-coded using annotations into EJB components.
  • 24. Annotations Usage Use javax.annotation.Resource Dependency injection of resources EJB, web, app client javax.ejb.EJB Dependency injection of session beans EJB, web, app client javax.jws.WebServiceRef Dependency injection of web services EJB, web, app client javax.persistence.PersistenceContext Dependency injection of container-managed EntityManager EJB, web javax.persistence.PersistenceUnit Dependency injection of EntityManagerFactory EJB, web javax.annotation.PostConstruct Lifecycle method EJB, web javax.annotation.PreDestroy Lifecycle method EJB, web javax.annotation.security.RunAs Security EJB, web javax.annotation.security.RolesAllowed Security EJB javax.annotation.security.PermitAll Security EJB javax.annotation.security.DenyAll Security EJB javax.annotation.security.DeclareRoles Security EJB, web
  • 25. Goal of dependency injection (DI) is to make component interdependencies as loosely coupled as possible. One component calls another component or resource only through an interface. The DI is JNDI lookup model reversed. In previous JNDI lookup model, the bean explicitly retrieves the resources and components which are hard-coded in the bean. In DI, the container reads the target bean configuration and gets the beans and resources needed by bean and injects them into the bean at runtime. It lets the container deal with the complexities of service or resource instantiation, initialization, sequencing, and supplies the service or resource references to the clients as required.
  • 26.
  • 27. Stateless session beans are used to model actions or processes that can be done in one shot. @Stateless—The @Stateless annotation tells the EJB container that declared Bean is a stateless session bean. The container automatically provides such services to the bean as automatic concurrency control, thread safety, pooling, and transaction management. @Local—The @Local annotation on the interface tells the container that the implementing EJB can be accessed locally through the interface. Alternatively, when marked with @Remote annotation, remote access through the @Remote annotation is provided under the hood by Java Remote Method Invocation (RMI).
  • 28. import javax.ejb.Stateless; import ejb3inaction.example.persistence.Bid; @Stateless public class PlaceBidBean implements PlaceBid { public PlaceBidBean() {} public Bid addBid(Bid bid) { System.out.println("Adding bid, bidder ID=" + bid.getBidderID() + ", item ID=" + bid.getItemID() + ", bid amount=" + bid.getBidAmount() + "."); return save(bid); } …. } ... import javax.ejb.Local; import ejb3inaction.example.persistence.Bid; @Local public interface PlaceBid { Bid addBid(Bid bid); }
  • 29. public class PlaceBidServlet extends HttpServlet { @EJB private PlaceBid placeBid; public void service(….) { Bid bid = new Bid(); bid.setBidderID(bidderID); …….. placeBid.addBid(bid); } } When the servlet container sees the @EJB annotation as servlet is first loaded, it looks up the PlaceBid EJB behind the scenes and sets the placeBid variable to the retrieved EJB reference. If necessary, the container will look up the EJB remotely over RMI by running the client in the application client container. The application client container is a mini Java EE container that can be run from the command line
  • 30. The @EJB annotation makes the container “instantiate” the placeBid variable with the EJB named PlaceBid before the variable is available for use. JNDI is the container registry that holds references to all container-managed resources such as EJBs. Clients gain access to session beans like the PlaceBid EJB directly or indirectly through JNDI as follows: Object ejbHome = new InitialContext().lookup("java:comp/env/PlaceBid"); PlaceBidHome placeBidHome = (PlaceBidHome) PortableRemoteObject.narrow(ejbHome, PlaceBidHome.class); PlaceBid placeBid = placeBidHome.create();
  • 31. Stateful session beans guarantee that a client can expect to set the internal state of a bean and count on the state being maintained between any number of method calls. The container ensures that a client can reach a bean dedicated to it across more than one method invocation. The container ensures that bean instance variable values are maintained for the duration of a session without your having to write any session maintenance code. In a stateful bean, the data the user enters at each step can be cached into bean variables until the workflow completes.
  • 32. import javax.ejb.*; @Stateful public class PlaceOrderBean implements PlaceOrder { private Long bidderID; private List<Long> items; private ShippingInfo shippingInfo; private BillingInfo billingInfo; public PlaceOrderBean () { items = new ArrayList<Long>(); } public void setBidderID(Long bidderId) { this.bidderId = bidderId; } public void addItem(Long itemId) { items.add(itemId); } ….. @Remove public Long confirmOrder() { Order order = new Order(); order.setBidderId(bidderId); order.setItems(items); order.setShippingInfo(shippingInfo); order.setBillingInfo(billingInfo); saveOrder(order); billOrder(order); return order.getOrderId(); }
  • 33. The @Remove annotation marks the end of the workflow modeled by a stateful bean. The container is told that there is no longer a need to maintain the bean’s session with the client after the confirmOrder method is invoked. If the container is never told what method invocation marks the end of the workflow, the container could wait for a long time until it could safely time-out the session. Since stateful beans are guaranteed to be dedicated to a client for the duration of a session, a lot of “orphaned” state data is consuming the precious server resources for long periods of time.
  • 34. @Stateful public class PlaceOrderBean implements PlaceOrder { @Resource(name="jms/QueueConnectionFactory") private ConnectionFactory connectionFactory; @Resource(name="jms/OrderBillingQueue") private Destination billingQueue; @Remove public Long confirmOrder() { Order order = new Order(); order.setBidderId(bidderId); order.setItems(items); saveOrder(order); billOrder(order); return order.getOrderId(); }
  • 35. private billOrder(Order order) { try { Connection connection = connectionFactory.createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageProducer producer = session.createProducer(billingQueue); ObjectMessage message = session.createObjectMessage(); message.setObject(order); producer.send(message); producer.close(); session.close(); connection.close(); } catch(Exception e){ e.printStackTrace(); }
  • 36. The @Resource annotation is much more general purpose and can be used to inject anything that the container knows about. The name parameter values specify what resources are bound to the EJB’s environment naming context.
  • 37. @MessageDriven( activationConfig = { @ActivationConfigProperty( propertyName="destinationName", propertyValue="jms/OrderBillingQueue") } ) public class OrderBillingMDB implements MessageListener { public void onMessage(Message message) { try { ObjectMessage objectMessage = (ObjectMessage) message; Order order = (Order) objectMessage.getObject(); try { bill(order); notifyBillingSuccess(order); order.setStatus(OrderStatus.COMPLETE); } catch (BillingException be) { notifyBillingFailure(be, order); order.setStatus(OrderStatus.BILLING_FAILED); } finally { update(order); } } catch (Exception e) { e.printStackTrace(); } }
  • 38. MDBs are not guaranteed to maintain state. The @MessageDriven annotation makes the container transparently provide messaging and other EJB services into a POJO. The activation configuration properties nested inside the @MessageDriven annotation informs MDB about the JMS destination to receive messages. MDBs implement the javax.jms.MessageListener interface which is used by container to invoke the MDB. The onMessage method defined by the interface has a single javax.jms.Message parameter that the container uses to pass(forward) a received message to the MDB.
  • 39. The JPA EntityManager interface defines the API for persistence while JPA entities specify how application data is mapped to a relational database. The @Entity annotation signifies the fact that the Class is a JPA entity. The @Table annotation tells JPA that the JPA entity is mapped to the corresponding SQL table The @Column annotations indicate which Entity properties map to which SQL table fields. The field mappings could have been placed directly onto member variables exposed through nonprivate access modifiers. The @Id annotation marks the corresponding property as the primary key for the Bid entity. The @GeneratedValue allows to automatically generate the primary key when the entity is saved into the database.
  • 40. @Entity @Table(name="BIDS") public class Bid implements Serializable { private Long bidID; private Long itemID; @Id @GeneratedValue(strategy=GenerationType.AUTO) @Column(name="BID_ID") public Long getBidID() { return bidID; } public void setBidID(Long bidID) { this.bidID = bidID; } @Column(name="ITEM_ID") public Long getItemID() { return itemID; } public void setItemID(Long itemID) { this.itemID = itemID; }
  • 41. The JPA EntityManager performs saving of the entity into the database by reading ORM configuration and providing entity persistence services through an API- based interface. The manager reads the ORM mapping annotations like @Table and @Column on the entity and figures out how to save the entity into the database. The EntityManager is injected into the PlaceBid bean through the @PersistenceContext annotation. The unitName parameter of the @PersistenceContext annotation points to the persistence unit of application. A persistence unit is a group of entities packaged together in an application module.
  • 42. The save method of EntityManager presists the data into the database issuing an SQL statement to insert a record in DB. public class PlaceBidBean implements PlaceBid { @PersistenceContext(unitName="actionBazaar") private EntityManager entityManager; ….. private Bid save(Bid bid) { entityManager.persist(bid); return bid; } }