Unit-4 Imp WT

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

.

UNIT -4

Q1. Illustrate Java Bean. Explain characteristics of java Bean. Give example.

Ans:

JavaBean :

A JavaBean is a reusable software component that follows specific conventions.

JavaBeans are used to encapsulate many objects into a single object (the bean), so
they can be passed around as a single unit.

This helps in building complex applications with a component-based architecture.

Characteristics of JavaBean

Properties:

JavaBeans have properties that can be read or written.

Properties can be of any Java data type, including other JavaBeans.

Getters and Setters:

Properties are accessed using getter and setter methods.

Getters and setters follow a naming convention: for a property named property, the
getter method would be getProperty() and the setter method would be setProperty(Type
property).

No-Argument Constructor:

JavaBeans provide a no-argument constructor, which allows them to be easily


instantiated.

Serializable:

JavaBeans implement the java.io.Serializable interface, which allows them to be


serialized (converted into a byte stream) so that their state can be saved and restored.

Event Handling:

JavaBeans can generate events and can be used in event-driven programming.

Example of a JavaBean

Below is an example of a simple JavaBean named Person:

import java.io.Serializable;

public class Person implements Serializable {


private String name;

private int age;

// No-argument constructor

public Person() {

// Getter for name

public String getName() {

return name;

// Setter for name

public void setName(String name) {

this.name = name;

// Getter for age

public int getAge() {

return age;

// Setter for age

public void setAge(int age) {

this.age = age;

// toString method for display


@Override

public String toString() {

return "Person{name='" + name + "', age=" + age + "}";

Q2. Define JDBC. Explain the Drivers used in JDBC. Create a JDBC Program for
Update and display the record of employees using prepared statement.

Ans:

JDBC (Java Database Connectivity)

Definition:

JDBC is an API (Application Programming Interface) for connecting and executing


queries with databases from Java programs.

It provides a standard interface for connecting to a wide range of relational databases.

JDBC allows Java applications to interact with databases to retrieve, insert, update, and
delete data.

JDBC Drivers

JDBC drivers are implementations that handle the communications between the Java
applications and the database.

There are four types of JDBC drivers:

Type 1: JDBC-ODBC Bridge Driver

This driver uses the ODBC driver to connect to the database.

It is not recommended for high-performance applications due to its reliance on native


code.

Example: sun.jdbc.odbc.JdbcOdbcDriver

Type 2: Native-API Driver (Partially Java Driver)

This driver converts JDBC calls into native calls of the database API.

It requires native database client libraries.

Example: oracle.jdbc.driver.OracleDriver

Type 3: Network Protocol Driver (Fully Java Driver)


This driver uses a middleware (application server) that converts JDBC calls to the
database-specific protocol.

It is suitable for internet-based applications.

Example: com.internetcds.jdbc.tds.Driver

Type 4: Thin Driver (Pure Java Driver)

This driver converts JDBC calls directly into the database-specific protocol.

It does not require any native libraries and is platform-independent.

Example: com.mysql.cj.jdbc.Driver

JDBC Program to Update and Display Employee Records using Prepared Statement

Below is an example of a JDBC program that updates and displays employee records
using PreparedStatement.

Prerequisites:

Ensure you have the JDBC driver for your database (e.g., MySQL JDBC driver).Set up your
database and table.

Here’s an example SQL for creating an employee table:

CREATE TABLE Employee (

id INT PRIMARY KEY,

name VARCHAR(100),

position VARCHAR(100),

salary DECIMAL(10, 2)

);

INSERT INTO Employee (id, name, position, salary) VALUES

(1, 'John Doe', 'Manager', 60000),

(2, 'Jane Smith', 'Developer', 50000);

Java Code:

import java.sql.*;

public class EmployeeDatabase {

// Database URL, username, and password


static final String DB_URL = "jdbc:mysql://localhost:3306/your_database";

static final String USER = "your_username";

static final String PASS = "your_password";

public static void main(String[] args) {

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

try {

// Step 1: Register JDBC driver

Class.forName("com.mysql.cj.jdbc.Driver");

// Step 2: Open a connection

conn = DriverManager.getConnection(DB_URL, USER, PASS);

// Step 3: Create a PreparedStatement to update an employee's salary

String updateSQL = "UPDATE Employee SET salary = ? WHERE id = ?";

pstmt = conn.prepareStatement(updateSQL);

pstmt.setBigDecimal(1, new BigDecimal(70000)); // New salary

pstmt.setInt(2, 1); // Employee ID to update

int rowsUpdated = pstmt.executeUpdate();

System.out.println("Rows updated: " + rowsUpdated);

// Step 4: Create a PreparedStatement to display all employee records

String selectSQL = "SELECT id, name, position, salary FROM Employee";

pstmt = conn.prepareStatement(selectSQL);

rs = pstmt.executeQuery();
// Step 5: Extract data from result set

while (rs.next()) {

// Retrieve by column name

int id = rs.getInt("id");

String name = rs.getString("name");

String position = rs.getString("position");

BigDecimal salary = rs.getBigDecimal("salary");

// Display values

System.out.print("ID: " + id);

System.out.print(", Name: " + name);

System.out.print(", Position: " + position);

System.out.println(", Salary: " + salary);

} catch (SQLException se) {

// Handle errors for JDBC

se.printStackTrace();

} catch (Exception e) {

// Handle errors for Class.forName

e.printStackTrace();

} finally {

// Finally block to close resources

try {

if (rs != null) rs.close();

if (pstmt != null) pstmt.close();

if (conn != null) conn.close();


} catch (SQLException se) {

se.printStackTrace();

Q3. What do you mean by Session Bean? Explain its types using suitable example.

Ans:

In the context of Enterprise JavaBeans (EJB), a Session Bean is a type of EJB that
represents a single client inside the EJB container.

Session Beans are used to implement business logic in a Java EE application and are
managed by the EJB container, providing services such as transaction management,
security, concurrency, and more.

Types of Session Beans

There are mainly two types of Session Beans:

1 Stateless Session Bean (SLSB)

2.Stateful Session Bean (SFSB)

Let's explore each type with suitable examples:

1. Stateless Session Bean (SLSB)

A Stateless Session Bean (SLSB) does not maintain conversational state with the
client across method invocations.

It is typically used for implementing stateless services or business logic that doesn't
require maintaining client-specific data between method calls.

Each method invocation on an SLSB is independent of previous invocations, and


the container can assign any available instance to handle the request.

Example of a Stateless Session Bean:

import javax.ejb.Stateless;

@Stateless

public class CalculatorBean {

public int add(int a, int b) {


return a + b;

public int subtract(int a, int b) {

return a - b;

// Other business methods

2. Stateful Session Bean (SFSB)

A Stateful Session Bean (SFSB) maintains conversational state with the client across
multiple method invocations.

This means that the bean instance preserves the data related to a specific client
session, allowing the client to maintain a stateful interaction with the bean.

SFSBs are suitable for scenarios where the client needs to maintain a
conversational state, such as shopping cart in an e-commerce application.

Example of a Stateful Session Bean:

import javax.ejb.Stateful;

@Stateful

public class ShoppingCartBean {

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

public void addItem(String item) {

items.add(item);

public List<String> getItems() {


return items;

public void clearCart() {

items.clear();

// Other business methods

Key Differences Between SLSB and SFSB:

State Management:

SLSB: Stateless, does not maintain client-specific state.

SFSB: Stateful, maintains conversational state with the client.

Concurrency:

SLSB: Instances can be shared among multiple clients concurrently.

SFSB: Each instance is dedicated to a single client session, managing state exclusively
for that client.

Lifecycle:

SLSB: Created and destroyed by the container based on demand.

SFSB: Created when a client requests it and destroyed when the client session ends or
explicitly removed.

You might also like