0% found this document useful (0 votes)
8 views14 pages

Unit 4

Uploaded by

Sajan Kunar
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)
8 views14 pages

Unit 4

Uploaded by

Sajan Kunar
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
You are on page 1/ 14

Web Technology (KCS 602)

Unit 4
Enterprise Java Bean: Preparing a Class to be a JavaBeans:

• A JavaBean is a reusable software component that can be manipulated


visually in a builder tool. It is a class that follows a specific naming convention
and has properties, methods, and events.
• To prepare a class to be a JavaBean, it must meet the following requirements:
o The class must be public.
o The class must have a no-argument constructor.
o The class must have properties that are accessible by get and set
methods.
o The class must have events that can be listened to.
• Once a class has been prepared to be a JavaBean, it can be used in a variety
of ways:
o It can be used in a builder tool to create a graphical user interface.
o It can be used in a web application to create dynamic content.
o It can be used in a standalone application to provide reusable
functionality.

Here is an example of a JavaBean class:

Code snippet
public class MyBean {

private String name;


private int age;

public MyBean() {
}

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

public int getAge() {


return age;
}

public void setAge(int age) {


this.age = age;
}

This class meets all of the requirements for a JavaBean. It is public, it has a no-
argument constructor, it has properties that are accessible by get and set methods,
and it has events that can be listened to.

Once this class has been compiled, it can be used in a variety of ways. For example,
it could be used in a builder tool to create a graphical user interface. The user could
then use the builder tool to set the name and age of the bean. The bean could then
be used in a web application to create dynamic content. For example, the bean could
be used to generate a page that displays the name and age of the user. The bean
could also be used in a standalone application to provide reusable functionality. For
example, the bean could be used to perform a calculation or to access a database.

JavaBeans are a powerful tool that can be used to create reusable software
components. By following the simple requirements outlined above, you can create
your own JavaBeans that can be used in a variety of ways.

creating a JavaBean:

1. Decide what your JavaBean will do. What kind of functionality will it provide?
What data will it store?
2. Design the interface for your JavaBean. What properties and methods will it
have? How will users interact with it?
3. Implement the code for your JavaBean. This includes creating the properties
and methods, as well as any other code that is necessary.
4. Test your JavaBean. Make sure that it works as expected.
5. Package your JavaBean. This involves creating a JAR file that contains the
JavaBean class and any other resources that it needs.
6. Deploy your JavaBean. This involves making the JAR file available to users
so that they can use it in their applications.

Here are some additional tips for creating JavaBeans:

• Use a naming convention that is consistent with other JavaBeans. This will
make it easier for users to find and use your JavaBean.
• Document your JavaBean. This will help users to understand how to use it.
• Use a version control system to track changes to your JavaBean. This will
help you to keep track of changes and to revert to a previous version if
necessary.
• Use a build automation tool to automate the process of building and
packaging your JavaBean. This will save you time and effort.
By following these tips, you can create high-quality JavaBeans that are easy to use
and deploy.

Here are some of the benefits of using JavaBeans:

• Reusability: JavaBeans are reusable software components that can be used


in a variety of applications.
• Portability: JavaBeans are platform-independent, so they can be used on any
platform that supports Java.
• Extensibility: JavaBeans can be extended by other developers, which makes
them a powerful tool for building custom applications.

If you are looking for a way to create reusable, portable, and extensible software
components, then JavaBeans are a great option.

JavaBeans properties:

• A JavaBean property is a named attribute that can be accessed by the user of


the object. The attribute can be of any Java data type, including the classes
that you define.
• Properties are accessed using get and set methods. The get method returns
the current value of the property, and the set method sets the value of the
property.
• Properties can be bound and constrained. A bound property notifies listeners
when its value changes. A constrained property allows listeners to veto
changes to the property.
• Properties can be indexed. An indexed property allows you to access
individual elements of a property.
• Properties can be nested. A nested property is a property that is contained
within another property.
• Properties can be transient. A transient property is not serialized when the
object is serialized.

Here is an example of a JavaBean property:

Code snippet
public class MyBean {

private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}

This class has a single property called name. The get and set methods for the name
property are used to access and set the value of the property.

Properties are a powerful feature of JavaBeans. They allow you to encapsulate data
and behavior, and they make your beans more reusable and easier to use.

Here are some additional tips for using JavaBean properties:

• Use descriptive names for your properties. This will make it easier for users to
understand what the property represents.
• Use consistent naming conventions for your properties. This will make it
easier for users to find and use your beans.
• Document your properties. This will help users to understand how to use
them.
• Use a version control system to track changes to your properties. This will
help you to keep track of changes and to revert to a previous version if
necessary.
• Use a build automation tool to automate the process of building and
packaging your beans. This will save you time and effort.
There are three main types of Java Beans:

• Session beans are objects that provide business logic for an application. They
are stateless, meaning that each client request creates a new instance of the
bean. This makes them ideal for tasks that are short-lived and do not require
persistent data.
• Entity beans represent persistent data in an application. They are stateful,
meaning that they maintain their state between client requests. This makes
them ideal for tasks that require access to long-lived data, such as storing
customer orders or tracking inventory levels.
• Message-driven beans are objects that receive and process messages from a
messaging system. They are stateless, meaning that each message creates a
new instance of the bean. This makes them ideal for tasks that are event-
driven, such as processing stock quotes or responding to customer inquiries.

In addition to these three main types, there are also a number of other types of Java
Beans, such as:

• Utility beans provide common functionality, such as data validation or logging.


• Web beans are designed to be used in web applications.
• Rich client beans are designed to be used in rich client applications, such as
desktop applications or mobile applications.

Java Beans are a powerful tool for developing modular, reusable, and scalable
applications. They can be used to create a wide variety of applications, from simple
command-line utilities to complex enterprise applications.

Here are some of the benefits of using Java Beans:

• Modularity: Java Beans are modular components that can be easily reused in
different applications.
• Reusability: Java Beans can be reused in different applications, which can
save time and development effort.
• Scalability: Java Beans can be scaled to meet the needs of large applications.
• Portability: Java Beans are portable to different platforms, which can make it
easier to develop and deploy applications.

If you are developing an application that requires modular, reusable, and scalable
components, then Java Beans are a good option to consider.

Stateless Session Beans


Stateless Session Beans (SSBs) are stateless, meaning that they do not maintain
any conversational state with the client. This makes them ideal for tasks that are
short-lived and do not require persistent data. SSBs are created and destroyed on
demand by the EJB container, and they are pooled to improve performance.

Here are some of the key features of SSBs:

• Stateless: SSBs do not maintain any conversational state with the client. This
means that each client request creates a new instance of the bean.
• Pooled: SSBs are pooled by the EJB container to improve performance.
When a client requests an SSB, the container will return an instance from the
pool if one is available. If no instances are available, the container will create
a new instance.
• Lightweight: SSBs are lightweight objects that do not require much memory or
resources. This makes them ideal for applications that need to scale to handle
a large number of concurrent requests.

Stateful Session Beans


Stateful Session Beans (SSBs) are stateful, meaning that they maintain
conversational state with the client. This makes them ideal for tasks that require
access to long-lived data, such as storing customer orders or tracking inventory
levels. SSBs are created and destroyed by the client, and they are not pooled by the
EJB container.

Here are some of the key features of SSBs:

• Stateful: SSBs maintain conversational state with the client. This means that
the bean can maintain data between client requests.
• Not pooled: SSBs are not pooled by the EJB container. This means that the
client is responsible for creating and destroying the bean.
• Heavyweight: SSBs are heavyweight objects that require more memory and
resources than stateless session beans. This makes them less ideal for
applications that need to scale to handle a large number of concurrent
requests.

Choosing Between Stateless and Stateful Session


Beans
The choice between stateless and stateful session beans depends on the specific
needs of the application. If the application does not require access to long-lived data,
then a stateless session bean is a good choice. If the application requires access to
long-lived data, then a stateful session bean is a good choice.

Which one should you use?


The choice between stateless and stateful session beans depends on the specific
needs of your application. If your application does not require conversational state,
then a stateless session bean is a good choice. If your application requires
conversational state, then a stateful session bean is a good choice.

Here are some additional factors to consider when making your decision:

• Performance: Stateless session beans are typically faster than stateful


session beans, as they do not need to maintain conversational state.
• Scalability: Stateless session beans are typically more scalable than stateful
session beans, as they can be pooled and reused by multiple clients.
• Complexity: Stateless session beans are typically simpler to develop and
maintain than stateful session beans.

Ultimately, the best choice for your application will depend on your specific needs
and requirements.

Entity beans:
Entity Beans are persistent objects that represent data in a database. They are
managed by the EJB container, which takes care of storing and retrieving them from
the database. Entity beans are typically used to represent business entities, such as
customers, orders, or products.

Here are some of the key features of Entity Beans:

• Persistence: Entity beans are persistent objects, which means that they can
be stored and retrieved from a database.
• State: Entity beans have state, which means that they can maintain their data
between client requests.
• Transactional: Entity beans are transactional, which means that they can be
used to perform business transactions.
• Object-oriented: Entity beans are object-oriented, which means that they can
be used to model business entities in a natural way.

Here are some of the benefits of using Entity Beans:

• Persistence: Entity beans provide a convenient way to store and retrieve data
from a database.
• State: Entity beans can maintain their data between client requests, which can
improve performance and scalability.
• Transactional: Entity beans can be used to perform business transactions,
which can improve data integrity.
• Object-oriented: Entity beans can be used to model business entities in a
natural way, which can improve the readability and maintainability of code.

Here are some of the drawbacks of using Entity Beans:

• Complexity: Entity beans can be complex to develop and maintain.


• Overhead: Entity beans can add overhead to applications, which can reduce
performance.
• Vendor lock-in: Entity beans are typically tied to a specific EJB container,
which can make it difficult to move applications to different vendors.

Overall, Entity Beans are a powerful tool for developing enterprise applications.
However, they can be complex to develop and maintain, and they can add overhead
to applications.

Here are some of the things to keep in mind when using Entity Beans:

• Design your entity beans carefully. Entity beans should be designed to


represent business entities in a natural way.
• Use the right persistence strategy. There are two main persistence strategies
for entity beans: container-managed persistence (CMP) and bean-managed
persistence (BMP). CMP is the recommended strategy, as it simplifies
development and maintenance.
• Use transactions carefully. Transactions can improve data integrity, but they
can also add overhead to applications. Use transactions only when
necessary.
• Use caching carefully. Caching can improve performance, but it can also add
complexity to applications. Use caching only when necessary.

Java Database Connectivity (JDBC): Merging Data from Multiple Tables

What is JDBC?

JDBC is a Java API that allows Java programs to connect to a database and execute
SQL statements. It is a standard API, so it can be used with any database that
supports JDBC drivers.

What is a join?

A join is a SQL statement that combines data from two or more tables. It is used to
create a virtual table that contains data from all of the joined tables.

How to merge data from multiple tables using JDBC

To merge data from multiple tables using JDBC, you can use the following steps:

1. Create a connection to the database.


2. Create a statement object.
3. Create a query that joins the tables.
4. Execute the query.
5. Iterate over the results of the query.
6. Close the connection.

Here is an example of how to merge data from two tables using JDBC:

import java.sql.*;

public class JDBCJoin {

public static void main(String[] args) throws SQLException {


// Create a connection to the database.
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"");

// Create a statement object.


Statement statement = connection.createStatement();

// Create a query that joins the tables.


String query = "SELECT * FROM customers JOIN orders ON customers.id
= orders.customer_id";

// Execute the query.


ResultSet resultSet = statement.executeQuery(query);

// Iterate over the results of the query.


while (resultSet.next()) {
// Get the data from the result set.
int customerId = resultSet.getInt("customer_id");
String customerName = resultSet.getString("customer_name");
int orderId = resultSet.getInt("order_id");
Date orderDate = resultSet.getDate("order_date");

// Do something with the data.


System.out.println(customerId + " " + customerName + " " +
orderId + " " + orderDate);
}

// Close the connection.


connection.close();
}
}

This code will merge the customers and orders tables and print out the customer ID,
customer name, order ID, and order date for each row in the result set.

Types of joins

There are different types of joins that can be used to merge data from multiple
tables. The most common types of joins are:

• Inner join: An inner join returns all rows from both tables where there is a
match between the columns.
• Outer join: An outer join returns all rows from the left table, even if there is no
match in the right table. It also returns all rows from the right table, even if
there is no match in the left table.
• Cross join: A cross join returns all possible combinations of rows from the two
tables.

Conclusion

JDBC is a powerful API that can be used to connect to a database and execute SQL
statements. It can also be used to merge data from multiple tables. By using JDBC,
you can easily access data from a database in your Java programs.
Joining, Manipulating Databases with JDBC

Joins

A join is a SQL statement that combines data from two or more tables. It is used to
create a virtual table that contains data from all of the joined tables.

There are different types of joins that can be used to merge data from multiple
tables. The most common types of joins are:

• Inner join: An inner join returns all rows from both tables where there is a
match between the columns.
• Outer join: An outer join returns all rows from the left table, even if there is no
match in the right table. It also returns all rows from the right table, even if
there is no match in the left table.
• Cross join: A cross join returns all possible combinations of rows from the two
tables.

Manipulating Databases with JDBC

JDBC can be used to manipulate data in a database. This includes creating,


updating, and deleting tables and rows.

To create a table, you can use the CREATE TABLE statement. The CREATE TABLE
statement takes a table definition as its argument. The table definition specifies the
columns that will be in the table, as well as the data types of the columns.

To update a row in a table, you can use the UPDATE statement. The UPDATE statement
takes a table name and a set of column-value pairs as its arguments. The column-
value pairs specify the columns that you want to update and the values that you want
to update them to.

To delete a row from a table, you can use the DELETE statement. The DELETE
statement takes a table name as its argument.

Conclusion

JDBC is a powerful API that can be used to connect to a database and execute SQL
statements. It can also be used to merge data from multiple tables and manipulate
data in a database. By using JDBC, you can easily access data from a database and
manipulate it in your Java programs.

Here are some additional notes on joining and manipulating databases with JDBC:
• When joining tables, it is important to specify the join condition. The join
condition is a Boolean expression that determines which rows from the two
tables will be combined.
• When updating or deleting rows, it is important to use the WHERE clause to
specify which rows you want to update or delete. The WHERE clause is a
Boolean expression that determines which rows will be affected by the update
or delete operation.
• It is important to close all database connections when you are finished using
them. This will free up resources and prevent database errors.

Java code for joining and manipulating databases with JDBC:

Java
import java.sql.*;

public class JDBCJoin {

public static void main(String[] args) throws SQLException {


// Create a connection to the database.
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"");

// Create a statement object.


Statement statement = connection.createStatement();

// Create a query that joins the tables.


String query = "SELECT * FROM customers JOIN orders ON customers.id
= orders.customer_id";

// Execute the query.


ResultSet resultSet = statement.executeQuery(query);

// Iterate over the results of the query.


while (resultSet.next()) {
// Get the data from the result set.
int customerId = resultSet.getInt("customer_id");
String customerName = resultSet.getString("customer_name");
int orderId = resultSet.getInt("order_id");
Date orderDate = resultSet.getDate("order_date");

// Do something with the data.


System.out.println(customerId + " " + customerName + " " +
orderId + " " + orderDate);
}

// Close the connection.


connection.close();
}
}

This code will merge the customers and orders tables and print out the customer ID,
customer name, order ID, and order date for each row in the result set.
Here is some additional Java code for updating and deleting rows in a database:

Java
import java.sql.*;

public class JDBCUpdateDelete {

public static void main(String[] args) throws SQLException {


// Create a connection to the database.
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root",
"");

// Create a statement object.


Statement statement = connection.createStatement();

// Update a row in the table.


String updateQuery = "UPDATE customers SET customer_name = 'John
Doe' WHERE id = 1";
statement.executeUpdate(updateQuery);

// Delete a row from the table.


String deleteQuery = "DELETE FROM customers WHERE id = 2";
statement.executeUpdate(deleteQuery);

// Close the connection.


connection.close();
}
}

This code will update the customer name for the customer with ID 1 to "John Doe"
and delete the customer with ID 2.

Prepared Statements
A prepared statement is a SQL statement that has been pre-compiled by the
database server. This means that when the statement is executed, the database
server does not need to parse and compile it again, which can improve performance.
Prepared statements are also more secure than dynamic SQL statements, because
they can help to prevent SQL injection attacks.

To use a prepared statement, you first need to create a PreparedStatement object.


This can be done using the DriverManager.prepareStatement() method. Once you
have created a PreparedStatement object, you can then set the values of the
parameters for the statement. This can be done using the setXXX() methods. Finally,
you can execute the statement using the execute() method.

Here is an example of how to use a prepared statement:

Code snippet
String sql = "SELECT * FROM customers WHERE name = ?";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, "John Doe");
ResultSet resultSet = statement.executeQuery();

In this example, we are creating a PreparedStatement object for the SQL statement
"SELECT * FROM customers WHERE name = ?". We are then setting the value of
the parameter for the statement to "John Doe". Finally, we are executing the
statement and getting the results back in a ResultSet object.

Transaction Processing
Transaction processing is a way of ensuring that database changes are either all
committed or all rolled back. This is important because it helps to protect data
integrity.

A transaction is a unit of work that either succeeds or fails as a whole. If a


transaction fails, all of the changes that were made during the transaction are rolled
back to their original state. This ensures that the database is always in a consistent
state.

There are two types of transactions:

• Atomic transactions: These transactions are all-or-nothing. Either all of the


changes are committed, or none of them are.
• Consistent transactions: These transactions ensure that the database is
always in a consistent state. This means that the database will never be in a
state where some data has been changed but other data has not.

Stored Procedures
A stored procedure is a collection of SQL statements that are stored in the database.
Stored procedures can be used to perform complex tasks, such as data
manipulation, reporting, and security.

Stored procedures can be used to improve performance, because they can be pre-
compiled and executed by the database server. Stored procedures can also be used
to improve security, because they can be used to restrict access to data.

Here is an example of a stored procedure:

Code snippet
create procedure update_customer (
in customer_id int,
in first_name varchar(255),
in last_name varchar(255)
)
begin
update customers
set first_name = ?,
last_name = ?
where customer_id = ?;
end;

In this example, we are creating a stored procedure called update_customer. This


stored procedure has three parameters: customer_id, first_name, and last_name.
The stored procedure updates the customer record with the specified customer_id
with the specified first_name and last_name.

Stored procedures can be called from within applications, or they can be called
directly from the database.

Summary
Prepared statements, transaction processing, and stored procedures are all
important concepts in database programming. Prepared statements can improve
performance and security, transaction processing can ensure data integrity, and
stored procedures can improve performance and security.

You might also like