Unit - 4
Enterprise Java Bean
Q1) How to Preparing a Class to be a JavaBeans?
A1) Preparing a Class to be a JavaBeans
JavaBeans are groups that combine multiple objects into a single one (the bean). It's a Java class that should adhere to the following guidelines:
● Serializable must be implemented.
● It should have a public constructor with no arguments.
● In a Java bean, all properties must be private, with public getter and setter methods.
Example
// Java program to illustrate the
// structure of JavaBean class
public class TestBean {
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
Setter methods have the following syntax:
● It should be open to the public.
● The form of the return should be void.
● The prefix set should be used before the setter process.
● It must take at least one argument; it must not be a no-arg process.
Getter method syntax is as follows:
● It should be open to the public.
● The return-type should not be void; instead, we must have a return-type that meets our requirements.
● The getter form must be preceded by the word get.
● It should not be subjected to debate.
The name of the getter method can be prefixed with either "get" or "is" for Boolean properties. However, it is suggested that you use the word "is."
// Java Program of JavaBean class
package geeks;
public class Student implements java.io.Serializable
{
private int id;
private String name;
public Student()
{
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
Q2) How to create a JavaBeans?
A2) Creating a JavaBeans
A Java bean is a Java class with private member variables, public getter and setter methods, and a public constructor that accepts zero arguments (supplied automatically by the compiler). Follow these seven steps to make a Java bean.
FirstName and lastName are two properties of the Java bean. A property is a private variable that can be accessed by other programs through getter and setter methods.
2. Person.java is the name you should give your file.
3. To build the class that will instantiate the Java bean, open your text editor. Fill in the blanks with the Java statements:
The software will generate a Java bean and then call the setter and getter methods on it.
4. CreateAJavaBean.java is the name of the file you can save.
5. Open a command prompt and go to the directory where your new Java programs are stored. Then press Enter to run the command to compile the Java bean source.
6. Enter the command to compile the Java program in order to instantiate the Java bean.
7. You're now able to put your Java software to the test. To run the Java runtime launcher, type the command and press Enter. Examine the information provided by your Java bean.
Q3) Write the properties of JavaBeans?
A3) Property of JavaBeans
A JavaBean property is a named function that the owner of the object may access. The function can be any Java data type, and it must contain the classes you specify.
A property on a JavaBean may be read, write, read-only, or write-only. Two methods in the JavaBean's implementation class are used to access JavaBean features:
1. getPropertyName ()
For example, if the property is called firstName, the method to read it is called getFirstName(). The accessor is the name for this tool.
2. setPropertyName ()
For example, if the property name is firstName, the method to write that property is setFirstName(). The mutator is the name of this tool.
A read-only attribute will have only one method, getPropertyName(), and a write-only attribute will have only one method, setPropertyName().
Advantages of JavaBeans
The following are some of JavaBean’s benefits: -
● Another program can access the JavaBean properties and methods.
● It makes reusing software components much easier.
Disadvantages of JavaBeans
The following are some of JavaBean's drawbacks:
● JavaBeans can be modified. As a result, it is unable to benefit from immutable artifacts.
● The boilerplate code can result from creating the setter and getter methods for each property separately.
Q4) Explain types of beans?
A4) Types of Beans
In Java, there are three types of beans:
It is further subdivided into two types.
● Stateful session beans
● Stateless session beans
2. Entity beans
3. Message Driven Beans (Message Beans).
Stateful Session beans
Like stateless session beans, a stateful session bean is a business object that reflects business logic. It does, however, keep the state (data). In other words, in a stateful session bean, the container maintains conversational state between multiple method calls.
The values of an object's instance variables make up its state. The instance variables in a stateful session bean reflect the state of a single client/bean session. This state is known as the conversational state since the client communicates (“talks”) with its bean.
A session bean is identical to an interactive session, as its name suggests. A session bean cannot be shared; it can only have one participant, just like an interactive session can only have one user. When a client closes, the session bean closes as well, and the client is no longer connected with it.
For the duration of the client/bean session, the state is maintained. The session ends and the state vanishes if the client removes the bean. However, the state's transient nature is not a problem because there is no need to keep the state after the client-bean conversation has ended.
Annotations used in stateful session beans
In a stateful session bean, there are five essential annotations:
Stateless Session beans
A stateless session bean is a single-purpose business object that only serves business logic. It isn't governed by a state (data). In other words, in the case of a stateless session bean, the container does not maintain conversational state between multiple method calls.
A stateless session bean does not keep track of the client's conversation. When a client calls a stateless bean's methods, the bean's instance variables contain a state that is unique to that client, but only for the duration of the call. The client-specific state should not be held after the process is completed. Clients may modify the state of instance variables in pooled stateless beans, and this state is carried over to the next invocation of the bean.
All instances of a stateless bean are identical except during method invocation, allowing the EJB container to assign an instance to any client. The EJB container pools the stateless bean objects in order to serve the request on request. Just one client can use it at a time. When multiple requests are made at the same time, the EJB container sends each one to a different instance.
Annotation used in stateless session beans
In a stateless session bean, there are three essential annotations:
Fig 1: life cycle of stateless session beans
Entity bean
The entity bean represents the database's persistent data. It's a server-side feature.
Bean controlled persistence (BMP) and container managed persistence (CMP) were the two forms of entity beans in EJB 2.x (CMP).
It has been discontinued since EJB 3.x, and has been replaced by JPA (Java Persistence API), which is covered in the hibernate tutorial. In the hibernate tutorial, there are examples of hibernate with annotations that use JPA annotations. Today, JPA and Hibernate are commonly used.
It summarizes the state of the database that can be saved. It is frowned upon. JPA has now taken its place (Java Persistent API). Entity beans are divided into two categories:
(i) Bean Managed Persistence: The programmer must write the code for database calls in a bean-controlled persistence form of entity bean. It continues to exist through several sessions and clients.
(ii) Container Managed Persistence: Container controlled storage is a database persistence business bean. The container manages database calls in container managed persistence.
Q5) Write short notes on JDBC?
A5) JDBC
Java Database Connectivity, or JDBC, is a basic Java API for database-independent connectivity between the Java programming language and a variety of databases.
Any of the tasks mentioned below that are commonly associated with database use have APIs in the JDBC library.
● Making a database relation.
● Creating SQL or MySQL statements is a common task.
● In the database, running SQL or MySQL queries.
● Viewing and editing the documents that result.
JDBC is a specification that defines a full set of interfaces for accessing an underlying database from a mobile device. Java can be used to create a variety of executables, including
● Applications written in Java
● Applets in Java
● Servlets in Java
● Server Pages in Java (JSPs)
● JavaBeans for Company (EJBs).
All of these executables may use a JDBC driver to connect to a database and use the information stored there.
JDBC is similar to ODBC in that it allows Java programs to contain database-independent code.
Q6) Define join?
A6) Joining
Java supports a variety of databases, and we'll need to include their respective jar files in the build path to allow JDBC connectivity. We must first determine which database we will use, and then add the jars accordingly. Other databases, such as Progress and Casandra, have jars that must be included in the construct course. Different types of joins are available in MySQL, and we can frame queries based on our needs.
Join is a form of join that allows two tables to be linked together based on a common field, resulting in the creation of a new virtual table.
Natural Join: It is a form of join that retrieves data from specified tables and matches it to a specific area.
Natural Left Join: Both tables are combined according to common fields in this process, but the priority is given to the first table in the database.
Natural Right Join: It is similar to Natural left join, but it retrieves data from the database's second table.
Q7) What do you mean by database with JDBC?
A7) Database with JDBC
To use JDBC to bind any Java program to a database, follow these five steps. These are the steps to take:
● Register the Driver class
● Create connection
● Create statement
● Execute queries
● Close connection
The driver class is registered using the Class class's forName() process. This method is used to load the driver class dynamically.
Syntax for forName() :
public static void forName(String className)throws ClassNotFoundException
2. Create the connection object
The DriverManager class's getConnection() method is used to create a database connection.
The getConnection() method's syntax :
● public static Connection getConnection(String url)throws SQLException
● public static Connection getConnection(String url,String name,String password) throws SQLException
3. Create the Statement object
To create a declaration, use the Connection interface's createStatement() process. The statement's object is in charge of running queries against the database.
Syntax:
public Statement createStatement()throws SQLException
4. Execute the query
The executeQuery() method of the Statement interface is used to run database queries. This method returns a ResultSet object that can be used to get all of a table's records.
Syntax
public ResultSet executeQuery(String sql)throws SQLException
5. Close the connection object
The ResultSet will be automatically closed when the relation object statement is closed. The Connection interface's close() method is used to close the connection.
Syntax
public void close()throws SQLException
Q8) What is prepared statements?
A8) Prepared statements
The PreparedStatement interface expands the Statement interface, providing additional functionality as well as a few benefits over a generic Statement object.
This statement allows you the ability to dynamically supply arguments.
Creating PreparedStatement Object
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age =? WHERE id =?";
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
. . .
}
The? symbol, also known as the parameter marker, is used to denote all parameters in JDBC. Before running the SQL statement, you must give each parameter a value.
The setXXX() methods bind values to input parameters, with XXX representing the Java data form of the value you want to bind. An SQLException will be thrown if the values are not supplied.
The ordinal location of each parameter marker is used to refer to it. Position 1 is represented by the first marker, position 2 by the second, and so on. This method is distinct from Java array indices, which begin at 0.
The PreparedStatement object supports all of the Statement object's methods for communicating with the database (a) execute(), (b) executeQuery(), and (c) executeUpdate()). The methods, on the other hand, have been updated to use SQL statements to input the parameters.
Closing PreparedStatement Object
For the same purpose that you should close a Statement object, you should also close the PreparedStatement object.
The job can be done with a single call to the close() process. If you close the Connection object first, the PreparedStatement object will be closed as well. To ensure proper cleanup, you should always specifically close the PreparedStatement item.
PreparedStatement pstmt = null;
try {
String SQL = "Update Employees SET age =? WHERE id =?";
pstmt = conn.prepareStatement(SQL);
. . .
}
catch (SQLException e) {
. . .
}
finally {
pstmt.close();
}
Q9) What is transaction processing?
A9) Transaction Processing
If your JDBC Connection is set to auto-commit, which it is by default, any SQL statement executed is committed to the database.
For simple applications, this might be perfect, but there are three reasons why you should disable auto-commit and handle your transactions yourself.
● In order to improve results.
● The dignity of business processes must be maintained.
● Distributed transfers are used.
You may use transactions to monitor whether and when changes to the database are made. It considers a single SQL statement or a group of SQL statements to be a single logical entity, and if either statement fails, the entire transaction fails.
Use the setAutoCommit() method of the Connection object to enable manual transaction support instead of the JDBC driver's default auto-commit mode. You can disable auto-commit by passing a boolean false to setAutoCommit(). To turn it back on, transfer true as a boolean value.
To switch off auto-commit, for example, if you have a Connection object called conn, write the following code.
conn.setAutoCommit(false);
Commit & Rollback
When you're finished with your changes and want to commit them, use the commit() method on the link object to do so.
conn.commit( );
Otherwise, use the following code to undo database changes made with the Link called conn.
conn.rollback( );
Example: for commit and rollback
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
String SQL = "INSERT INTO Employees " +
"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback();
}
Q10) Explain stored procedures?
A10) Stored Procedures
It will provide you with more information on JDBC SQL escape syntax.
A Connection object produces the Statement and Prepared Statement objects, as well as the Callable Statement object, which is used to call a database stored procedure.
Creating Callable Statement Object
Assume you need to run the Oracle stored procedure below.
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;
Since the above stored procedure was written for Oracle, we are using MySQL, so we will write the same stored procedure for MySQL as follows to build it in the EMP database.
DELIMITER $$
DROP PROCEDURE IF EXISTS EMP.getEmpName $$
CREATE PROCEDURE EMP.getEmpName
(IN EMP_ID INT, OUT EMP_FIRST VARCHAR(255))
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END $$
DELIMITER;
There are three types of parameters: IN, OUT, and INOUT. Only the IN parameter is used by the Prepared Statement object. All three can be used by the Callable Statement object.
The following are the meanings for each parameter.
IN: When the SQL statement is made, a parameter whose value is unknown. The setXXX() methods are used to connect values to IN parameters.
OUT: The SQL statement it returns provides the value for this parameter. The getXXX() methods are used to extract values from the OUT parameters.
INOUT: A parameter that can be used for both input and output. The setXXX() and getXXX() methods are used to bind variables and retrieve values.
Q11) Write the advantages of JavaBeans?
A11) advantages of Java Beans
Standard frameworks for dealing with software building blocks are provided by a software component architecture. Some of the basic benefits that Java technology provides for component developers are mentioned below:
● Many of the advantages of Java's "write-once, run-anywhere" model are available to a Bean.
● It is possible to monitor the resources, activities, and methods of a Bean that are exposed to an application builder tool.
● A Bean can be built to function in a variety of environments, making it useful in global markets.
● Auxiliary applications can be made available to aid in the configuration of a Bean. This program is only needed when the component's design-time parameters are being set.
● A Bean's configuration settings can be saved in permanent storage and later restored.
● A Bean can be configured to receive events from other objects and to send events to other objects.
Q12) Write the advantages of JDBC?
A12) Advantages of JDBC
The following are some of the benefits of using:
● It has the ability to read any database. The only prerequisite for it to do so is that all of the drivers be properly installed.
● It extracts data from the database and converts it to XML format.
● It does not necessitate the conversion of the content.
● It fully supports queries and stored procedures.
● Both synchronous and asynchronous processing are supported.
● Modules are supported.
Q13) What are the components of JDBC?
A13) Components of JDBC
The JDBC API includes the following interfaces and classes, which can also be referred to as components:
● Driver Manger - The Driver Manager class is in charge of handling the database's list of drivers, as its name suggests. It also uses a sub-protocol of communication to balance link requests from the java application and the database driver. To bind to a database, the first driver that recognizes the subprotocol under JDBC is used.
● Driver - The Driver is the interface that manages the interactions between the application and the database server. The chances of directly communicating with Driver objects are extremely rare, as most of the time the Driver Manager objects are used to handle objects of this kind. It extracts all of the detail=[]- associated with the operation of Driver properties.
● Connection - For contacting the database, the link interface and all methods are used. The object of connection reflects the contact context, i.e., the object of connection is the only way to communicate with the database.
● Statements - The artifacts that are generated from this interface will allow the SQL statements to be submitted to the database. When executing stored procedures, some of the derived interfaces also accept parameters.
Q14) Write the disadvantages of JDBC?
A14) Disadvantages of JDBC
Like the majority of APIs, has some drawbacks. Some of these drawbacks are mentioned below:
● When it comes to the driver, it is extremely responsive. As a result, it is critical to install and deploy the correct drivers for each form of database in order to use it. This is a time-consuming and at times difficult job.
● It is not possible to update or insert several tables with a single sequence.