You are on page 1of 17

JavaBeans

JavaBeans is a portable, platform-independent model written in Java Programming Language. Its


components are referred to as beans.

In simple terms, JavaBeans are classes which encapsulate several objects into a single object. It
helps in accessing these object from multiple places. JavaBeans contains several elements like
Constructors, Getter/Setter Methods and much more.

JavaBeans has several conventions that should be followed:

 Beans should have a default constructor (no arguments)

 Beans should provide getter and setter methods

o A getter method is used to read the value of a readable property

o To update the value, a setter method should be called

 Beans should implement java.io.serializable, as it allows to save, store and restore the
state of a JavaBean you are working on

Now that you are familiar with basics, let’s learn in detail about the properties of JavaBeans.

JavaBean Properties
A JavaBean property can be accessed by the user of the object. The feature can be of any Java
data type, containing the classes that you define. It may be of the following mode: read, write,
read-only, or write-only. JavaBean features are accessed through two methods:

1. getEmployeeName ()

For example, if the employee name is firstName, the method name would be getFirstName() to
read that employee name. This method is known as an accessor. Properties of getter methods are
as follows:

1. Must be public in nature


2. Return-type should not be void
3. The getter method should be prefixed with the word get
4. It should not take any argument
2.setEmployeeName ()
For example, if the employee name is firstName, the method name would be setFirstName() to
write that employee name. This method is known as a mutator. Properties of setter methods:

1. Must be public in nature


2. Return-type should be void
3. The setter method has to be prefixed with the word set
4. It should take some argument
Now that you have attained some theoretical knowledge about JavaBeans, let us move on and
understand the implementation process.

Writing a Simple Bean


In this section you will learn more about Beans and the BeanBox by

 Creating a simple Bean


 Compiling and saving the Bean into a Java Archive (JAR) file
 Loading the Bean into the ToolBox
 Dropping a Bean instance into the BeanBox
 Inspecting the Bean's properties, methods, and events
 Generating an introspection report

Your Bean will be named SimpleBean. Here are the steps to create it and view it in the BeanBox:

1. Write the SimpleBean code. Put it in a file named SimpleBean.java, in the directory
of your choice. Here's the code:

import java.awt.*;
import java.io.Serializable;

public class SimpleBean extends Canvas


implements Serializable
{
//Constructor sets inherited properties
public SimpleBean(){
setSize(60,40);
setBackground(Color.red);
}
}
SimpleBean extends the java.awt.Canvas component. SimpleBean also implements
the java.io.Serializable interface, a requirement for all Beans. SimpleBean sets the background
color and component size.
Make sure the CLASSPATH environment variable is set to point to all needed .class (or .jar)
files. Here are some URLs that will help you to set CLASSPATH correctly:
a. The Managing Source and Class Files lesson gives good advice on how
and when to set your CLASSPATH.
b. The JDK Tool Reference Page provides complete CLASSPATH information for
both Windows and Solaris platforms.
2.Compile the Bean:

javac SimpleBean.java
This produces the class file SimpleBean.class

3.Create a manifest file. Use your favorite text editor to create a file, we'll call
it manifest.tmp, that contains the following text:
Name: SimpleBean.class
Java-Bean: True

4.Create the JAR file. The JAR file will contain the manifest and the SimpleBean class
file:

jar cfm SimpleBean.jar manifest.tmp SimpleBean.class

5.Load the JAR file into the ToolBox. Select the File|LoadJar... menu item. This will bring
up a file browser. Navigate to the SimpleBean.jar location and select it. SimpleBean will
appear at the bottom of the ToolBox. (Note that when the BeanBox is started, all Beans in
JAR files in the beans/jars directory are automatically loaded into the ToolBox).

6.Drop a SimpleBean instance into the BeanBox. Click on the word SimpleBean in the
ToolBox. The cursor will change to a crosshair. Move the cursor to a spot within the BeanBox
and click. SimpleBean will appear as a painted rectangle with a hatched border. This border
means that SimpleBean is selected. The SimpleBean properties will appear in the Properties
sheet.

Advantages of JavaBeans
The following list enumerates some of the benefits 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.
Disadvantages of JavaBeans
1. JavaBeans are mutable, hence lack the advantages offered by immutable objects.

2. JavaBeans will be in inconsistent state partway through its construction.

Manifest File
The manifest is a special file named `MANIFEST. MF` and resides within the `META-INF`
directory of a JAR file. This file provides a multitude of capabilities that influence the
behavior, discoverability, and structure of the encapsulated JavaBeans components.

JAR files
JAR files can be used for packaging related class files, serialized Beans, and other resources.
This scheme allows multiple Beans to be packaged in a single JAR file, providing a convenient
way to share common class files and resources. Optionally, a JAR file may contain a manifest
describing its contents.

Enterprise Java Beans (EJB)


Enterprise Java Beans (EJB) is one of the several Java APIs for standard manufacture of
enterprise software. EJB is a server-side software element that summarizes business logic of an
application. Enterprise Java Beans web repository yields a runtime domain for web related
software elements including computer reliability, Java Servlet Lifecycle (JSL) management,
transaction procedure and other web services. The EJB enumeration is a subset of the Java EE
enumeration.
The EJB enumeration was originally developed by IBM in 1997 and later adopted by Sun
Microsystems in 1999 and enhanced under the Java Community Process.
The EJB enumeration aims to provide a standard way to implement the server-side business
software typically found in enterprise applications. Such machine code addresses the same
types of problems, and solutions to these problems are often repeatedly re-implemented by
programmers. Enterprise Java Beans is assumed to manage such common concerns as
endurance, transactional probity and security in a standard way that leaves programmers free to
focus on the particular parts of the enterprise software at hand.
To run EJB application we need an application server (EJB Container) such as Jboss,
Glassfish, Weblogic, Websphere etc. It performs:
1. Life cycle management
2. Security
3. Transaction management
4. Object pooling
Types of Enterprise Java Beans
There are three types of EJB:
1. Session Bean: Session bean contains business logic that can be invoked by local, remote or
webservice client. There are two types of session beans: (i) Stateful session bean and (ii)
Stateless session bean.

 (i) Stateful Session bean :


Stateful session bean performs business task with the help of a state. Stateful session bean
can be used to access various method calls by storing the information in an instance
variable. Some of the applications require information to be stored across separate method
calls. In a shopping site, the items chosen by a customer must be stored as data is an
example of stateful session bean.

 (ii) Stateless Session bean :


Stateless session bean implement business logic without having a persistent storage
mechanism, such as a state or database and can used shared data. Stateless session bean can
be used in situations where information is not required to used across call methods.

2. Message Driven Bean: Like Session Bean, it contains the business logic but it is invoked
by passing message.
3. Entity Bean: It summarizes the state that can be remained in the database. It is deprecated.
Now, it is replaced with JPA (Java Persistent API). There are two types of entity bean:

 (i) Bean Managed Persistence :


In a bean managed persistence type of entity bean, the programmer has to write the code for
database calls. It persists across multiple sessions and multiple clients.

 (ii) Container Managed Persistence :


Container managed persistence are enterprise bean that persists across database. In
container managed persistence the container take care of database calls.

Use Enterprise Java Beans

1.Application needs Remote Access. In other words, it is distributed.


2.Application needs to be scalable. EJB applications supports load balancing, clustering and
fail-over.
3.Application needs encapsulated business logic. EJB application is differentiated from
demonstration and persistent layer.
Advantages of Enterprise Java Beans
1. EJB repository yields system-level services to enterprise beans, the bean developer can
focus on solving business problems. Rather than the bean developer, the EJB repository is
responsible for system-level services such as transaction management and security
authorization.
2. The beans rather than the clients contain the application’s business logic, the client
developer can focus on the presentation of the client. The client developer does not have to
code the pattern that execute business rules or access databases. Due to this the clients are
thinner which is a benefit that is particularly important for clients that run on small devices.
3. Enterprise Java Beans are portable elements, the application assembler can build new
applications from the beans that already exists.

Disadvantages of Enterprise Java Beans


1. Requires application server
2. Requires only java client. For other language client, you need to go for webservice.
3. Complex to understand and develop EJB applications.

EJB Architecture

The EJB architecture has two main layers, i.e., Application Server and EJB Container, based
on which the EJB architecture exist. The graphical representation of the EJB architecture is given
below.

In the above diagram, the logical representation of how EJBs are invoked and deployed by using
RMI(Remote Method Invocation) is defined. The containers of the EJB cannot be self-deployed.
In order to deploy the containers, it requires the Application server.
Java JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC
drivers to connect with the database. There are four types of JDBC drivers:
o JDBC-ODBC Bridge Driver,
o Native Driver,
o Network Protocol Driver, and
o Thin Driver
.
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

The current version of JDBC is 4.3. It is the stable release since 21st September, 2017. It is based
on the X/Open SQL Call Level Interface. The java.sql package contains classes and interfaces
for JDBC API. A list of popular interfaces of JDBC API are given below:
o Driver interface
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
JDBC Driver
JDBC Driver is a software component that enables java application to interact with the
database. There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)
1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use
JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.
Advantage:
o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
o The Native driver needs to be installed on the each client machine.
o The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
o No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.

Advantage:
o Better performance than all other drivers.
o No software is required at client side or server side.

Disadvantage:
o Drivers depend on the Database.

Main classes and interfaces of JDBC

JDBC API is available in two packages java.sql, core API and javax.sql JDBC optional
packages. Following are the important classes and interfaces of JDBC.

DriverManager This class manages the JDBC drivers. You need to


register your drivers to this.
It provides methods such as registerDriver() and
getConnection().

Driver This interface is the Base interface for every


driver class i.e. If you want to create a JDBC
Driver of your own you need to implement this
interface. If you load a Driver class
(implementation of this interface), it will create an
instance of itself and register with the driver
manager.

Statement This interface represents a static SQL statement.


Using the Statement object and its methods, you
can execute an SQL statement and get the results
of it.
It provides methods such as execute(),
executeBatch(), executeUpdate() etc. To execute
the statements.

PreparedStatement This represents a precompiled SQL statement. An


SQL statement is compiled and stored in a
prepared statement and you can later execute this
multiple times. You can get an object of this
interface using the method of the Connection
interface named prepareStatement(). This provides
methods such as executeQuery(),
executeUpdate(), and execute() to execute the
prepared statements and getXXX(), setXXX()
(where XXX is the datatypes such as long int float
etc..) methods to set and get the values of the bind
variables of the prepared statement.

CallableStatement Using an object of this interface you can execute


the stored procedures. This returns single or
multiple results. It will accept input parameters
too. You can create a CallableStatement using the
prepareCall() method of the Connection interface.
Just like Prepared statement, this will also provide
setXXX() and getXXX() methods to pass the
input parameters and to get the output parameters
of the procedures.

Connection This interface represents the connection with a


specific database. SQL statements are executed in
the context of a connection.This interface provides
methods such as close(), commit(), rollback(),
createStatement(), prepareCall(),
prepareStatement(), () setSavepoint() etc.

ResultSet This interface represents the database result set, a


table which is generated by executing statements.
This interface provides getter and update methods
to retrieve and update its contents respectively.

ResultSetMetaData This interface is used to get the information about


the result set such as, number of columns, name of
the column, data type of the column, schema of
the result set, table name, etc
It provides methods such as getColumnCount(),
getColumnName(), getColumnType(),
getTableName(), getSchemaName() etc.

Java Database Connectivity with 5 Steps


There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:

o Register the Driver class


o Create connection
o Create statement
o Execute queries
o Close connection

Java Database Connectivity with MySQL

To connect Java application with the MySQL database, we need to follow 5 following steps.

In this example we are using MySql as the database. So we need to know following
informations for the mysql database:

1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
2. Connection URL: The connection URL for the mysql database
is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database,
localhost is the server name on which mysql is running, we may also use IP address,
3306 is the port number and sonoo is the database name. We may use any database, in
such case, we need to replace the sonoo with our database name.
3. Username: The default username for the mysql database is root.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.

Let's first create a table in the mysql database, but before creating table, we need to create
database first.

1. create database sonoo;


2. use sonoo;
3. create table emp(id int(10),name varchar(40),age int(3));

Example to Connect Java Application with mysql database

In this example, sonoo is the database name, root is the username and password both.

1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();
10. ResultSet rs=stmt.executeQuery("select * from emp");
11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }

The above example will fetch all the records of emp table.

To connect java application with the mysql database, mysqlconnector.jar file is required to be
loaded.

download the jar file mysql-connector.jar

Two ways to load the jar file:


1. Paste the mysqlconnector.jar file in jre/lib/ext folder
2. Set classpath

1) Paste the mysqlconnector.jar file in JRE/lib/ext folder:


Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.

2) Set classpath:
There are two ways to set the classpath:

o temporary
o permanent

How to set the temporary classpath


open command prompt and write:

1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;

How to set the permanent classpath

Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.;
as C:\folder\mysql-connector-java-5.0.8-bin.jar;.;

There are 5 steps to connect any java application with the database using
JDBC

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used
to dynamically load the driver class.

Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.

Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection with the
database.

Syntax of getConnection() method


public static Connection getConnection(String url)throws SQLException
public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.

Syntax of createStatement()
methodpublic Statement createStatement()throws SQLException
Example to create the statement object
Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql)throws SQLException


Example to execute query
ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.

Syntax of close() method


public void close()throws SQLException
Example to close connection
con.close();

Java Database Connectivity with Oracle


To connect java application with the oracle database, we need to follow 5 following steps. In
this example, we are using Oracle 10g as the database. So we need to know following
information for the oracle database:

1. Driver class: The driver class for the oracle database


is oracle.jdbc.driver.OracleDriver.
2. Connection URL: The connection URL for the oracle10G database
is jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database,
thin is the driver, localhost is the server name on which oracle is running, we may also
use IP address, 1521 is the port number and XE is the Oracle service name. You may
get all these information from the tnsnames.ora file.
3. Username: The default username for the oracle database is system.
4. Password: It is the password given by the user at the time of installing the oracle
database.

Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the
SQL query to create a table.

1. create table emp(id number(10),name varchar2(40),age number(3));

Example to Connect Java Application with Oracle database

In this example, we are connecting to an Oracle database and getting data from emp table.
Here, system and oracle are the username and password of the Oracle database.

import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");

//step2 create the connection object


Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

//step3 create the statement object


Statement stmt=con.createStatement();

//step4 execute query


ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

//step5 close the connection object


con.close();

}catch(Exception e){ System.out.println(e);}

}
}

You might also like