0% found this document useful (0 votes)
18 views13 pages

Unit 4 Important Topics

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)
18 views13 pages

Unit 4 Important Topics

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/ 13

1.

Enterprise Java Beans (EJB):


Enterprise Java Beans (EJB) is one of the several Java APIs for standard manufacture of
enterprise so ware. EJB is a server-side so ware element that summarizes business logic of
an applica on. Enterprise Java Beans web repository yields a run me domain for web
related so ware elements including computer reliability, Java Servlet Lifecycle (JSL)
management, transac on procedure and other web services. The EJB enumera on is a
subset of the Java EE enumera on.
The EJB enumera on aims to provide a standard way to implement the server-side business
so ware typically found in enterprise applica ons. Such machine code addresses the same
types of problems, and solu ons to these problems are o en repeatedly re-implemented by
programmers. Enterprise Java Beans is assumed to manage such common concerns as
endurance, transac onal probity and security in a standard way that leaves programmers
free to focus on the par cular parts of the enterprise so ware at hand.
To run EJB applica on we need an applica on server (EJB Container) such as Jboss, Glassfish,
Weblogic, Websphere etc. It performs:
1. Life cycle management
2. Security
3. Transac on 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 informa on in an instance
variable. Some of the applica ons require informa on 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 situa ons where informa on 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. En ty 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 en ty
bean:
(i) Bean Managed Persistence :
In a bean managed persistence type of en ty bean, the programmer has to write the code
for database calls. It persists across mul ple sessions and mul ple 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.
When to use Enterprise Java Beans
1.Applica on needs Remote Access. In other words, it is distributed.
2.Applica on needs to be scalable. EJB applica ons supports load balancing,
clustering and fail-over.
3.Applica on needs encapsulated business logic. EJB applica on is differen ated
from demonstra on 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 transac on management
and security authoriza on.
2. The beans rather than the clients contain the applica on’s business logic, the client
developer can focus on the presenta on of the client. The client developer does not
have to code the pa ern that execute business rules or access databases. Due to this
the clients are thinner which is a benefit that is par cularly important for clients that
run on small devices.
3. Enterprise Java Beans are portable elements, the applica on assembler can build
new applica ons from the beans that already exists.
Disadvantages of Enterprise Java Beans
1. Requires applica on server
2. Requires only java client. For other language client, you need to go for webservice.
3. Complex to understand and develop EJB applica ons.
2.Stateful vs Stateless session bean:

3. Difference between Statement and PreparedStatement :

Statement PreparedStatement
It is used when SQL query is to be It is used when SQL query is to be executed
executed only once. multiple times.

You can not pass parameters at


runtime. You can pass parameters at runtime.
Used for CREATE, ALTER, DROP Used for the queries which are to be executed
statements. multiple times.

Performance is very low. Performance is better than Statement.

It is base interface. It extends statement interface.

Used to execute normal SQL queries. Used to execute dynamic SQL queries.

We can not use statement for reading We can use Preparedstatement for reading
binary data. binary data.

It is used for DDL statements. It is used for any SQL Query.

We can not use statement for writing We can use Preparedstatement for writing
binary data. binary data.

No binary protocol is used for


communication. Binary protocol is used for communication.

JDBC Drivers:
JDBC Driver is a so ware component that enables java applica on to interact with the
database. There are 4 types of JDBC drivers:
1) Type I or 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 func on 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:

 easy to use.
 can be easily connected to any database.
Disadvantages:

 Performance degraded because JDBC method call is converted into the ODBC
func on calls.
 The ODBC driver needs to be installed on the client machine.

2) Type II or Na ve-API driver (partially java driver):


The Na ve API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into na ve calls of the database API. In order to interact with different database,
this driver needs their local API, that’s why data transfer is much more secure as compared to
type-1 driver. It is not wri en en rely in java.

Advantage:

 performance upgraded than JDBC-ODBC bridge driver.


Disadvantage:

 The Na ve driver needs to be installed on the each client machine.


 The Vendor client library needs to be installed on client machine.

3) Type III or Network Protocol driver (fully java driver):


The Network Protocol driver uses middleware (applica on server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully wri en in java.
Advantage:

 No client side library is required because of applica on server that can perform many
tasks like audi ng, load balancing, logging etc.
Disadvantages:

 Network support is required on client machine.


 Requires database-specific coding to be done in the middle er.
 Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle er.

4) Type IV or Thin driver (fully java driver):


Type-4 driver is also called na ve protocol 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
wri en in Java language.

Advantage:

 Be er performance than all other drivers.


 No so ware is required at client side or server side.
Disadvantage:

 Drivers depend on the Database.


Steps to Connect Java Applica on with Database:
Below are the steps that explains how to connect to Database in Java:
 Step 1 – Import the Packages
 Step 2 – Load the drivers using the forName() method
 Step 3 – Register the drivers using DriverManager
 Step 4 – Establish a connec on using the Connec on class object
 Step 5 – Create a statement
 Step 6 – Execute the query
 Step 7 – Close the connec ons

Retrieve contents of a table using JDBC connec on in java:

//Step 1: Import the database packages


import java.sql.*;

public class jdbcResultSet {


public static void main(String[] args) {
try {
//Step 2 – Load the drivers using the forName() method
Class.forName("org.apache.derby.jdbc.ClientDriver");
}
catch(ClassNotFoundException e) {
System.out.println("Class not found "+ e);
}
try {

//Step 3 & 4 – Establish a connec on using the Connec on class objectRegister the
drivers using DriverManager
Connection con = DriverManager.getConnection(
"jdbc:derby://localhost:1527/testDb","username", "password");

// Step 5– Create a Statement


Statement stmt = con.createStatement();

// Step 6– Execute the result


ResultSet rs = stmt.executeQuery("SELECT * FROM employee");
System.out.println("id name job");

while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
} catch(SQLException e) {
System.out.println("SQL exception occured" + e);
}
}
}

Result:
The above code sample will produce the following result. The result may vary.

id name job
1 alok trainee
2 ravi trainee

Example 2: create, alter & drop SQL commands to create, edit or delete table.

import java.sql.*;

public class jdbcConn


{
public sta c void main(String[] args) throws Excep on
{
Class.forName("org.apache.derby.jdbc.ClientDriver");
Connec on con = DriverManager.getConnec on(
"jdbc:derby://localhost:1527/testDb","username", "password");

Statement stmt = con.createStatement();


// to create the table
String query ="CREATE TABLE employees(id INTEGER PRIMARY KEY,
first_name CHAR(50), last_name CHAR(75))";
stmt.execute(query);
System.out.println("Employee table created");
// to edit a table
String query1 = "ALTER TABLE employees ADD address CHAR(100) ";
stmt.execute(query1);
// to delete columns in a table
String query2 = "ALTER TABLE employees DROP COLUMN last_name";
stmt.execute(query2);

System.out.println("Address column added to the table & last_name column removed


from the table");
// to delete the table
String query3 = "drop table employees";
stmt.execute(query3);
System.out.println("Employees table removed");
}
}

Result:
The above code sample will produce the following result. The result may vary.

Employee table created


Address column added to the table & last_name
column removed from the table
Employees table removed from the database

Example 3: update, delete & insert SQL commands to edit or delete row contents.

import java.sql.*;

public class updateTable {


public sta c void main(String[] args) {
try {
Class.forName("org.apache.derby.jdbc.ClientDriver");
} catch(ClassNotFoundExcep on e) {
System.out.println("Class not found "+ e);
}
try {
Connec on con = DriverManager.getConnec on (
"jdbc:derby://localhost:1527/testDb","username", "password");

Statement stmt = con.createStatement();


String query1 = "update emp set name = 'ravi' where id = 2";
String query2 = "delete from emp where id = 1";
String query3 = "insert into emp values (1,'ronak','manager')";

stmt.execute(query1);
stmt.execute(query2);
stmt.execute(query3);

ResultSet rs = stmt.executeQuery("SELECT * FROM emp");


System.out.println("id name job");

while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String job = rs.getString("job");
System.out.println(id+" "+name+" "+job);
}
} catch(SQLExcep on e) {
System.out.println("SQL excep on occured" + e);
}
}
}

Result:
The above code sample will produce the following result. The result may vary.

id name job
2 ravi trainee
1 ronak manager

JavaBeans:
A JavaBean is a Java class that should follow the following conven ons:

 It should have a no-arg constructor.


 It should be Serializable.
 It should provide methods to set and get the values of the proper es, known as
ge er and se er methods.
Why use JavaBean?
According to Java white paper, it is a reusable so ware component. A bean encapsulates
many objects into one object so that we can access this object from mul ple places.
Moreover, it provides easy maintenance.
Simple example of JavaBean class
//Employee.java

package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
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;}
}
How to access the JavaBean class?
To access the JavaBean class, we should use ge er and se er methods.

package mypack;
public class Test{
public sta c void main(String args[]){
Employee e=new Employee();//object is created
e.setName("Arjun");//se ng value to the object
System.out.println(e.getName());
}}

JavaBean Proper es
A JavaBean property is a named feature that can be accessed by the user of the object. The
feature can be of any Java data type, containing the classes that you define.
A JavaBean property may be read, write, read-only, or write-only. JavaBean features are
accessed through two methods in the JavaBean's implementa on class:
1. getPropertyName ()
For example, if the property name is firstName, the method name would be getFirstName()
to read that property. This method is called the accessor.
2. setPropertyName ()
For example, if the property name is firstName, the method name would be setFirstName()
to write that property. This method is called the mutator.

Advantages of JavaBean
The following are the advantages of JavaBean:

 The JavaBean proper es and methods can be exposed to another applica on.
 It provides an easiness to reuse the so ware components.
Disadvantages of JavaBean
The following are the disadvantages of JavaBean:
 JavaBeans are mutable. So, it can't take advantages of immutable objects.
 Crea ng the se er and ge er method for each property separately may lead to the
boilerplate code.

jsp:useBean ac on tag:
The jsp:useBean ac on tag is used to locate or instan ate a bean class. If bean object of
the Bean class is already created, it doesn't create the bean depending on the scope. But
if object of bean is not created, it instan ates the bean.
Syntax of jsp:useBean ac on tag
<jsp:useBean id= "instanceName" scope= "page | request | session | applica on"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>

A ributes and Usage of jsp:useBean ac on tag

 id: is used to iden fy the bean in the specified scope.


 scope: represents the scope of the bean. It may be page, request, session or
applica on. The default scope is page.
 page: specifies that you can use this bean within the JSP page. The default scope
is page.
 request: specifies that you can use this bean from any JSP page that processes the
same request. It has wider scope than page.
 session: specifies that you can use this bean from any JSP page in the same session
whether processes the same request or not. It has wider scope than request.
 applica on: specifies that you can use this bean from any JSP page in the same
applica on. It has wider scope than session.
 class: instan ates the specified bean class (i.e. creates an object of the bean class)
but it must have no-arg or no constructor and must not be abstract.
 type: provides the bean a data type if the bean already exists in the scope. It is
mainly used with class or beanName a ribute. If you use it without class or
beanName, no bean is instan ated.
 beanName: instan ates the bean using the java.beans.Beans.instan ate()
method.

Simple example of jsp:useBean ac on tag


For the example of setProperty, getProperty and useBean tags, visit next page.
Calculator.java (a simple Bean class)
package com.javatpoint;
public class Calculator{
public int cube(int n){return n*n*n;}
}
index.jsp file
<jsp:useBean id="obj" class="com.javatpoint.Calculator"/>
<% int m=obj.cube(5);
out.print("cube of 5 is "+m); %>

You might also like