0% found this document useful (0 votes)
6 views24 pages

JavaBeans and EJB Overview Guide

The document provides an overview of JavaBeans and Enterprise JavaBeans (EJB), detailing their structure, properties, advantages, and disadvantages. It explains the components of a JavaBean, the types of EJBs, and their roles in various applications, emphasizing their importance in enterprise-level development. Additionally, it outlines the differences between stateless and stateful session beans, as well as the concept of entity beans for persistence in databases.

Uploaded by

Kavya Bhatia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views24 pages

JavaBeans and EJB Overview Guide

The document provides an overview of JavaBeans and Enterprise JavaBeans (EJB), detailing their structure, properties, advantages, and disadvantages. It explains the components of a JavaBean, the types of EJBs, and their roles in various applications, emphasizing their importance in enterprise-level development. Additionally, it outlines the differences between stateless and stateful session beans, as well as the concept of entity beans for persistence in databases.

Uploaded by

Kavya Bhatia
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

UNIT 4

Enterprise Java Bean, [Link],


[Link] with MongoDB

~SONALI KUMARI
What is a JavaBean?
• A JavaBean is a reusable software component written in Java that follows
specific conventions to allow easy manipulation, configuration, and reuse in
development environments.
➢ In simple terms:
A JavaBean is a class that encapsulates many objects into a single object (the
bean). It is serializable, has a no-argument constructor, and allows access to
properties through getter and setter methods.
Components of a JavaBean:
• Properties – Fields with getter/setter methods.
• Events – Mechanisms that allow beans to communicate (event handling
model).
• Methods – Functions defined inside the bean.
• Persistence – Ability to save and restore bean state using serialization.
Properties of java beans class are:
• All JavaBean instance variabls shoud be private.
• The javabean class must have a no-arg constructor.
• All javabeean properties must have public getter and setter methods.
• The javabean class implement serializable interface.(optional)
• Here following step-by-step JavaBean properties:
Step-1: Create a Public Class
A Java Bean must be a public class, so it can be accessed from other classes.
Step-2: Define Private Properties
The properties (fields) of the class must be private to encapsulate the data.
Step-3: Provide Public Getter and Setter Methods
Use public methods to allow controlled access to the properties.
These methods follow the naming convention:
getPropertyName for retrieving a value.
setPropertyName for updating a value.
Setter and Getter Methods in Java
Properties for setter methods:
• It should be public in nature.
• The return type a should be void.
• The setter method should be prefixed with the set.
• It should take some argument i.e. it should not be a no-arg method.
Properties for getter methods:
• It should be public in nature.
• The return type should not be void i.e. according to our
requirement, return type we have to give the return type.
• The getter method should be prefixed with get.
• It should not take any argument.
Step-4: Provide a No-Argument • Flow of a JavaBean
Constructor
A no-argument constructor is required 1. Create Bean Object
to instantiate the bean class without Employee emp = new Employee();
providing initial values.
2. Set Properties (Write)
Step-5: Implement Serializable
(Optional) [Link](101);
Java Beans often implement the [Link]("John");
Serializable interface to allow their
instances to be serialized. [Link](50000);
Step-6: Add Additional Methods 3. Get Properties (Read)
You can include utility methods like [Link]([Link]());
toString(), equals(), or hashCode() for 4. Serialize (Optional)
debugging or comparisons
Save bean state to a file or stream.
5. Deserialize (Optional)
Load bean state back for reuse.

.
• Example 1. of JavaBean Class • // Java program to access JavaBean class
// Java Program of JavaBean class • package btech;
• package btech; // Driver Class
• public class Student implements • public class Test {
[Link] { • public static void main(String args[]) //
• private int id; main function
• private String name; • {
• public Student() {} // Constructor • Student s = new Student(); // object is
• public void setId(int id) { [Link] = id; } // created
Setter for Id • [Link]("GFG"); // setting value to the
• public int getId() { return id; } // Getter for object
Id • [Link]([Link]());
• public void setName(String name) { • }
[Link] = name; } // Setter for Name • }
• public String getName() { return name; }
• } // Getter for Name
Example 2. Program: Implementation of JavaBeans
• import [Link]; // Getter and Setter for 'name'
• public String getName() {
• public class Employee implements Serializable { • return name;
• private int id; • }
• private String name; • public void setName(String name) {
• private double salary; • [Link] = name;
• }
// No-argument constructor
• public Employee() {} // Getter and Setter for 'salary'
• public double getSalary() {
// Getter and Setter for 'id' • return salary;
• public int getId() { • }
• return id; • public void setSalary(double salary) {
• } • [Link] = salary;
• public void setId(int id) { • }
• [Link] = id; • }
• }
• How to Use a JavaBean: • [Link]("Employee ID:
• public class TestBean { " + [Link]());
• public static void main(String[] args) • [Link]("Employee
{ Name: " + [Link]());
• Employee emp = new Employee(); • [Link]("Employee
Salary: " + [Link]());
• }
// Setting values using setter
methods •}
• [Link](101); • Output:
• [Link]("John Doe"); • Employee ID: 101
• [Link](75000); • Employee Name: John Doe
• Employee Salary: 75000.0
// Accessing values using getter
methods
Advantages of JavaBeans
❑Portable
JavaBeans components are built purely in Java, hence are fully portable to any platform that supports
the Java Run-Time Environment. All platform specifics, as well as support for JavaBeans, are
implemented by the Java Virtual Machine.
❑Compact and Easy
JavaBeans components are simple to create and easy to use. This is an important focus sector of the
JavaBeans architecture. It doesn’t take much effort to write a simple Bean. Also, a bean is lightweight,
so, it doesn’t have to carry around a lot of inherited baggage to support the Beans environment.
❑Carries the Strengths of the Java Platform
• JavaBeans is pretty compatible, there isn’t any new complicated mechanism for registering
components with the run-time system.
• Though all these sound good, using JavaBeans presents some disadvantages as well. Now, let’s check
out what those would be.
Disadvantages of JavaBeans
• JavaBeans are mutable, hence lack the advantages offered by immutable objects.
• JavaBeans will be in inconsistent state partway through its construction.
• No business logic, Primarily used for data encapsulation, not complex processing.
• Verbosity: Requires many boilerplate getters/setters.
• Less Modern Approach
How JavaBeans Are Used in Real Life
Application Type JavaBean Role
Beans store user data, session data (e.g.,
JSP/Servlets (Web Apps)
UserBean, LoginBean).

Beans represent UI components or


Swing/JavaFX (GUI Apps)
configuration settings.

Beans provide business logic and


Enterprise Apps (EJB)
transaction management.

Use POJOs similar to JavaBeans for


Frameworks (Spring, Hibernate)
dependency injection or ORM.
Types of JavaBeans
1. Simple JavaBeans:
Basic beans that store data and are used as DTOs (Data Transfer Objects).
Example: Employee, Student, Product, etc.
2. Enterprise JavaBeans (EJB):
• Used in enterprise-level applications (server-side).
• Provide services like transactions, security, persistence, etc.
• Types of EJBs:
• Session Beans
• Entity Beans
• Message-Driven Beans
INTRODUCTION TO EJB
• An Enterprise Java Bean is a server-side components which encapsulates business logic.
• EJB is used to develop scalable, robust and secured enterprise application in Java.
• Services such as security, transaction management etc. are provided by EJB container to
all EJB applications.
• To run EJB application we need an application server (EJB Container) such as Jboss,
Glassfish, Weblogic, Websphere etc.
It performs:
Life cycle management, Security, Transaction management, Object pooling,Distributed
Scalable.
• BUT (important point) — the developer doesn’t code any of those features manually.
• The server (EJB Container) provides those services.
EJB application is developed on the server, so it is also called server-side components.
• WHERE IS EJB USED TODAY?
• banking core system
• trading platform settlement
• telecom rating + billing
• airline reservation
• insurance underwriting
WHY DOES EJB EXIST?
Before EJB, companies would create their own: connection, pooling
transaction systems,security frameworks,clustering,distributed invocations
Huge corporations (banks, telecom, airline) cannot afford bugs in those areas.
• That is why Sun (now Jakarta EE) made EJB so these things are guaranteed
correct. So a developer only writes business logic like:
calculate price,apply discount,evaluate insurance risk,debit account,create
invoice. Everything else is automatically serviced by container.
• The EJB container is the part of the application server that runs EJBs and
provides all of the enterprise-level services automatically.
Advantages of EJB
• transaction gets handled automatically
• built-in security is available.
• performance is better because of pooling
• business logic becomes separate / reusable
• helpful in big enterprise applications.
• remote calling is possible in distributed systems.

Disadvantages of EJB
• setup and configuration is difficult.
• it cannot run without an EJB container.
• it is heavy technology for small projects (overkill)
• learning curve is high.
• compared to Spring in modern time, it feels a bit old.
Session bean
• Session bean encapsulates business logic only, it can be invoked by local, remote and
webservice client.
• It can be used for calculations, database access etc.
• The life cycle of session bean is maintained by the application server (EJB Container).
Types of Session Bean:
1. Stateless Session Bean:
• A Stateless Session Bean (SLSB) is a type of EJB that does NOT keep any client state
(data) between method calls. Each call is independent.
• It is called Stateless Because it never remembers anything about the previous
request.
• It can be accessed by one client at a time,each and every request is independent.
• Container can reuse the same object instances for many clients.
• No state stored between calls.
e.g.
• login verify,
• tax calculate,
• bill generate Example
Client 1 -> calculates GST
@Stateless Client 2 -> calculates GST
public class CalculatorBean imple Client 3 -> calculates GST
ments Calculator { The bean does not store any values
public int add(int a, int b) { per user.
return a + b;
}}
2. STATEFUL SESSION BEAN
• A Stateful Session Bean is an EJB that remembers data for ONE particular client across multiple method
calls.
• Stateful bean holds client-specific data in its instance fields.
• Example:
shopping cart → it keeps items added by ONE user.
• Stateless bean forgets everything.
Stateful bean remembers.
• Example:
client 1 →
• addItem("Shoes")
• addItem("Watch")
client 2 →
• addItem("Camera")
each client sees different cart because state is unique per client.
WHEN TO USE STATEFUL EJB?
for multi-step processes:

Real world
why stateful?
example
shopping cart
user adds items in steps
(Amazon, Flipkart)
loan/insurance
7 screens → next → next → next
application wizard
online tax filing progressive data entry
hotel booking hold selected rooms + dates temporarily
• import [Link];
• import [Link];
• import [Link];

• @Stateful
• public class CartBean {

• private List<String> items = new ArrayList<>();

• public void addItem(String item){


• [Link](item);
• }

• public List<String> showCart(){


• return items;
• }
• }
Entity bean
• Entity beans are objects that represents a persistence storage mechanism.
• Each entity beans has underlying table in a relational database and each
row in the table represents the instance of the bean.
• User data can be saved to database via entity beans and later on can be
retrieved from the database in the entity bean.
• Example:
• CUSTOMER table → Customer entity bean
• PRODUCT table → Product entity bean
❖ Entity bean = persistent object
✓ Meaning → its state is stored permanently
in database.
Important point
• Today we don’t use “Entity Bean” (deprecated).
Now we use JPA Entity:
• @Entity
• public class Customer { … }
why entity bean existed? because developers wanted:
• object oriented representation of table rows.
• container to handle persistence automatically.
• EJB container used to handle:
• insert
• update
• delete
• find
• transactions
Automatically.
• Real world meaning
domain example
Banking Account entity mapped to ACCOUNT table
Ecommerce Product entity mapped to PRODUCT table
HR system Employee entity mapped to EMP table

import [Link];
import [Link];

@Entity
public class Product {
@Id
private int id;
private String name;
private double price;
}

You might also like