0% found this document useful (0 votes)
5 views

Unit 4

Uploaded by

Varun Tyagi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Unit 4

Uploaded by

Varun Tyagi
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 84

JavaBeans

• An introduction to component-based
development in general
• Introduction to JavaBeans
– Java components
– client-side
• Working with the BDK
• The beans development life cycle
• Writing simple and advanced beans
1 5/1/2023
Software Components

• All engineering discplines use components to build


systems. In SE we rely on line-by-line SD.
• We have class libraries
– create objects from class libraries
– we still need to write a large amount of code
– objects are not enough

2 5/1/2023
Software Components

• They are like Integrated Circuit (IC)


components
• Over 20 years ago, hardware vendors learned how
to package transistors
• Hardware Engineers integrate ICs to make a
board of chips
• In SE, we are where hardware engineers were 20
years ago
• We are building software routines
3 5/1/2023
Java Components

• Instead of worrying about rotuines, we can buy


routines and use/reuse them in our applications
(assemble applications)
• JavaBeans -- portable, platform-independent
component model
• Java components are known as beans
• A bean: a reusable software component that can
be manipulated visually in a builder tool

4 5/1/2023
JavaBeans vs. Class Libraries

• Beans are appropriate for software components


that can be visually manipulated

• Class libraries are good for providing functionality


that is useful to programmers, and doesn’t benefit
from visual manipulation

5 5/1/2023
JavaBeans Concepts

• A component is a self-contained reusable


software unit
• Components expose their features (public
methods and events) to builder tools
• A builder tool maintains Beans in a palette or
toolbox.

6 5/1/2023
Concepts...

• You can select a bean from the toolbox, drop it in a


form, and modify its appearance and behavior.
• Also, you can define its interaction with other
beans
• ALL this without a line of code.

7 5/1/2023
JavaBean Characteristics

• a public class with 0-argument constuctor


• it has properties with accessory methods
• it has events
• it can customized
• its state can be saved
• it can be analyzed by a builder tool

8 5/1/2023
Key Concepts….

• Properties can be customized at design-time.


Customization can be done:
– using property editor
– using bean customizers
• Events are used when beans want to
intercommunicate
• Persistence: for saving and restoring the
state
• Bean’s methods are regular Java
9 methods. 5/1/2023
Security Issues

• JavaBeans are sbject to the standard Java


security model
• The security model has neither extended nor
relaxed.
• If a bean runs as an untrusted applet then it will be
subject to applet security
• If a bean runs as a stand-alone application
then it will be treated as a normal Java
application.
10 5/1/2023
JavaBeans and Threads

• Assume your beans will be running in a multi-


threaded environment
• It is your responsibility (the developer) to make
sure that their beans behave properly under multi-
threaded access
• For simple beans, this can be handled by
simply making all methods …...

1 5/1/2023
1
Beans Development Kit (BDK)

• To start the BeanBox:


– run.bat (Windows)
– run.sh (Unix)

12 5/1/2023
BDK

• ToolBox contains the beans available


• BeanBox window is the form where you
visually wire beans together.
• Properties sheet: displays the properties for the
Bean currently selected within the BeanBox
window.

13 5/1/2023
MyFirstBean

• import java.awt.*;
• import java.io.Serializable;
• public class FirstBean extends Canvas implements
Serializable {
 public FirstBean() {
 setSize(50,30);
 setBackground(Color.blue);
 }
• }
14 5/1/2023
First Bean

• Compile: javac FirstBean.java


• Create a manifest file:
• FirstBean.mft
– Name: FirstBean.class
– Java-Bean: True

• Create a jar file:


• jar -cfm FirstBean.jar FirstBean.mft FirstBean.class

15 5/1/2023
SecondBean

import java.awt.*;
import java.io.Serializable; private String msg;
import java.util.*; public SecondBean()
public class SecondBean {
extends Canvas implements msg="Hello Class";
Serializable setSize(200,30);
setBackground(Color.blue);
}
public void setMsg(String msg)
{
this.msg=msg;
}
public String getMsg()
{
return msg;
}
public void paint(Graphics g)
{
g.drawString(msg,10,10);
16 } } 5/1/2023
Properties

• Bean’s appearance and behavior --


changeable at design time.
• They are private values
• Can be accessed through getter and setter
methods
• getter and setter methods must follow some
rules -- design patterns (documenting
experience)

17 5/1/2023
Properties

• A builder tool can:


– discover a bean’s properties
– determine the properties’ read/write attribute
– locate an appropriate “property editor” for each type
– display the properties (in a sheet)
– alter the properties at design-time

18 5/1/2023
Types of Properties

• Simple
• Index: multiple-value properties
• Bound: provide event notification when value
changes
• Constrained: how proposed changes can be
okayed

19 5/1/2023
Enterprise Java Beans ( EJB )

• EJB (Enterprise Java Bean) is used to develop


scalable, robust and secured enterprise
applications in java.

• Unlike RMI, middleware services such as


security, transaction management etc. are
provided by EJB Container to all EJB
applications.

20 5/1/2023
Enterprise Java Beans ( EJB )

• The current version of EJB is EJB 3.2. The


development of EJB 3 is faster than EJB 2 because
of simplicity and annotations such as @EJB,
@Stateless, @Stateful, @ModelDriven,
@PreDestroy, @PostConstruct etc.

21 5/1/2023
Enterprise Java Beans ( EJB )

• EJB is an acronym for enterprise java bean. It


is a specification provided by Sun Microsystems
to develop secured, robust and scalable
distributed applications.

22 5/1/2023
Enterprise Java Beans ( EJB )

• To run EJB application, you need an application


server (EJB Container) such as Jboss, Glassfish,
Weblogic, Websphere etc. It performs:
a) life cycle management,
b) security,
c) transaction management, and
d) object pooling.

23 5/1/2023
Enterprise Java Beans ( EJB )

• EJB application is deployed on the server, so it is


called server side component also.
• EJB is like COM (Component Object Model)
provided by Microsoft. But, it is different from
Java Bean, RMI and Web Services.

24 5/1/2023
When use Enterprise Java Bean?

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 separated from
presentation and persistent layer.

25 5/1/2023
Types of Enterprise Java Bean

There are 3 types of enterprise bean in java.


1. Session Bean: Session bean contains business logic that
can be invoked by local, remote or webservice client.
2. Message Driven Bean: Like Session Bean, it
contains the business logic but it is invoked by
passing message.
3. Entity Bean: It encapsulates the state that can be
persisted in the database. It is deprecated. Now, it is
replaced with JPA (Java Persistent API).

26 5/1/2023
Difference between RMI and EJB

Both RMI and EJB, provides services to access


an object running in another JVM (known as
remote object) from another JVM. The
differences between RMI and EJB are given
below:

27 5/1/2023
Difference between RMI and EJB

28 5/1/2023
EJB and Webservice

• In EJB, bean component and bean client both


must be written in java language.
• If bean client need to be written in other language
such as .net, php etc, we need to go with
webservices (SOAP or REST). So EJB with
web service will be better option.

29 5/1/2023
Disadvantages of EJB

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.

30 5/1/2023
Session Bean

• Session bean encapsulates business logic only,


it can be invoked by local, remote and
webservice client.
• It can be used for calculations, database
access etc.
• The life cycle of session bean is maintained by the
application server (EJB Container).

31 5/1/2023
Types of Session Bean

There are 3 types of session bean.


1) Stateless Session Bean: It doesn't maintain
state of a client between multiple method calls.
2) Stateful Session Bean: It maintains state of a
client across multiple requests.
3) Singleton Session Bean: One instance per
application, it is shared between clients and
supports concurrent access.

32 5/1/2023
Stateless Session Bean

 Stateless Session bean is a business object that


represents business logic only. It doesn't have state
(data).
• In other words, conversational state between multiple
method calls is not maintained by the container in case of
stateless session bean.
• The stateless bean objects are pooled by the EJB
container to service the request on demand.
• It can be accessed by one client at a time. In case of
concurrent access, EJB container routes each request to
33 different instance.
5/1/2023
Annotations used in Stateless
Session Bean

There are 3 important annotations used in


stateless session bean:
1. @Stateless
2. @PostConstruct
3. @PreDestroy

34 5/1/2023
Life cycle of Stateless Session
Bean

• There is only two states of stateless session bean:


does not exist and ready. It is explained by the
figure given below.

35 5/1/2023
Life cycle of Stateless Session
Bean

36 5/1/2023
Life cycle of Stateless Session
Bean

• EJB Container creates and maintains a pool of


session bean first. It injects the dependency if then
calls the @PostConstruct method if any. Now
actual business logic method is invoked by the
client. Then, container calls @PreDestory method
if any. Now bean is ready for garbage collection.

37 5/1/2023
Stateful Session Bean

• Stateful Session bean is a business object


that represents business logic like stateless
session bean. But, it maintains state (data).
• In other words, conversational state between
multiple method calls is maintained by the
container in stateful session bean.

38 5/1/2023
Annotations used in Stateful
Session Bean

There are 5 important annotations used in


stateful session bean:
1. @Stateful
2. @PostConstruct
3. @PreDestroy
4. @PrePassivate
5. @PostActivate

39 5/1/2023
Life Cycle of a Stateful Session
Bean

40 5/1/2023
Entity Bean

• Entity bean represents the persistent data


stored in the database. It is a server-side
component.
• In EJB 2.x, there was two types of entity beans:
bean managed persistence (BMP) and
container managed persistence (CMP).
• Since EJB 3.x, it is deprecated and replaced by JPA
(Java Persistence API) that is covered in the
hibernate tutorial.
41 5/1/2023
JDBC
Java Database Connectivity

19-04-2023 1
What is JDBC?
• “An API that lets you access virtually any
tabular data source from the Java
programming language”
• “Tabular data source is an access of virtually
any data source, from relational databases to
spreadsheets and flat files.”

19-04-2023 2
General Architecture

19-04-2023 3
JDBC Drivers

There are 4 types of JDBC drivers:


1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

19-04-2023 4
Type-1 driver
• Type-1 driver or 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.
• Type-1 driver is also called Universal driver
because it can be used to connect to any of
the databases.

19-04-2023 5
Type-1 driver
• As a common driver is used in order to interact with
different databases, the data transferred through this
driver is not so secured.
• The ODBC bridge driver is needed to be installed in
individual client machines.
• Type-1 driver isn’t written in java, that’s why it isn’t a
portable driver.
• This driver software is built-in with JDK so no need to
install separately.
• It is a database independent driver.
19-04-2023 6
Type-2 driver
• The Native API driver uses the client -side
libraries of the database.
• This driver converts JDBC method calls into
native 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.

19-04-2023 7
Type-2 driver
• Driver needs to be installed separately in
individual client machines
• The Vendor client library needs to be installed
on client machine.
• Type-2 driver isn’t written in java, that’s why it
isn’t a portable driver
• It is a database dependent driver.

19-04-2023 8
Type-3 driver
• The Network Protocol driver uses middleware
(application server) that converts JDBC calls
directly or indirectly into the vendor-specific
database protocol.
• Here all the database connectivity drivers are
present in a single server, hence no need of
individual client-side installation.

19-04-2023 9
Type-3 driver
• Type-3 drivers are fully written in Java, hence they
are portable drivers.
• No client side library is required because of
application server that can perform many tasks like
auditing, load balancing, logging etc.
• Network support is required on client machine.
• Maintenance of Network Protocol driver becomes
costly because it requires database-specific coding to
be done in the middle tier.
• Switch facility to switch over from one database to
19-04a-20n23other 10

database.
Type-4 driver
• Type-4 driver is also called native protocol
driver.
• This driver interact directly with database.
• It does not require any native database library,
that is why it is also known as Thin Driver.
• Does not require any native library and
Middleware server, so no client-side or server-
side installation.
• It is fully written in Java language, hence they
are portable drivers.
19-04-2023 11
Which Driver to use When?
• If you are accessing one type of database, such as
Oracle, Sybase, or IBM, the preferred driver type is
type-4.
• If your Java application is accessing multiple types of
databases at the same time, type 3 is the preferred
driver.
• Type 2 drivers are useful in situations, where a type 3
or type 4 driver is not available yet for your database.
• The type 1 driver is not considered a deployment-
level driver, and is typically used for development
and testing purposes only.
19-04-2023 12
Some Basic Rules for database
Connectivity in any Platform
• Import the necessary packages
• Register the Driver Manager
• Establish the connection with database
• Create the statements or sql queries which we
want to execute on database.
• Now execute the statements
• Close the connection

19-04-2023 13
Basic steps to use
a database in
Java
• 1.Register DriverManager
• 2.Establish a connection
• 3.Create JDBC Statements
• 4.Execute SQL Statements
• 5.GET ResultSet
• 6.Close connections

19-04-2023 14
1. Register DriverManager
• import java.sql.*;
• Load the driver for JDBC/ODBC bridge
• Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
• Load the vendor specific driver
– Class.forName("oracle.jdbc.driver.OracleDriver");
• What do you think this statement does, and how?
• Dynamically loads a driver class, for Oracle database

19-04-2023 15
2. Establish a connection
• Make the connection
– Connection con =
DriverManager.getConnection( "jdbc:odbc:dataso
urcename", username, passwd);

19-04-2023 16
3. Create JDBC statement(s)
• Statement stmt = con.createStatement() ;
• Creates a Statement object for sending SQL
statements to the database

19-04-2023 17
4.Executing SQL Statements
• String strInsert = "Insert into
tableName(Col Names)
values(123456789,abc,100)";
stmt.executeUpdate(strIns
ert);

19-04-2023 18
5.Get ResultSet
String strSelect = "select * from tableName";

ResultSet rs = Stmt.executeQuery(strSelect);
//What does this statement do?

while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
}

19-04-2023 19
6.Close connection
• stmt.close();
• con.close();

19-04-2023 20
PreparedStatement

• The PreparedStatement interface is a


subinterface of Statement. It is used to
execute parameterized query.
• String sql="insert into emp
values(?,?,?)";
• As you can see, we are passing parameter (?)
for the values. Its value will be set by calling
the setter methods of PreparedStatement.

19-04-2023 21
• Improves performance: The performance of
the application will be faster if you use
PreparedStatement interface because query is
compiled only once.

19-04-2023 22
Example of PreparedStatement
interface that inserts the
record
• PreparedStatement
stmt=con.prepareStatement("insert into Emp
values(?,?)");
• stmt.setInt(1,101);//1 specifies the first
parameter in the query
• stmt.setString(2,"Ratan");

19-04-2023 23
Example of PreparedStatement
interface that updates the record
• PreparedStatement
stmt=con.prepareStatement("update emp set
name=? where id=?");
• stmt.setString(1,"Sonoo");//1 specifies the
first parameter in the query i.e. name
• stmt.setInt(2,101);

19-04-2023 24
Example of PreparedStatement
interface that deletes the record
• PreparedStatement
stmt=con.prepareStatement("delete from
emp where id=?");
• stmt.setInt(1,101);

19-04-2023 25
Example of PreparedStatement
interface that retrieve the records
of a table
PreparedStatement stmt
=con.prepareStatement("select * from emp");
ResultSet rs=stmt.executeQuery();
while(rs.next())
{ System.out.println(rs.getInt(1)+“

+rs.getString(2));
}
19-04-2023 26
Transaction Management in JDBC
• Transaction represents a single unit of work.
• The ACID properties describes the transaction
management well. ACID stands for Atomicity,
Consistency, isolation and durability.
• Atomicity means either all successful or none.
• Consistency ensures bringing the database from one
consistent state to another consistent state.
• Isolation ensures that transaction is isolated from
other transaction.
• Durability means once a transaction has been
committed, it will remain so, even in the event of
errors, power loss etc.
19-04-2023 27
fast performance It makes the performance fast
because database is hit at the time of commit.

19-04-2023 28
In JDBC, Connection interface
provides methods to manage
transaction.

19-04-2023 29
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into
user420
values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420
values(191,'umesh',50000)");
con.commit();
con.close();

19-04-2023 30
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420
values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420
values(191,'umesh',50000)");
System.out.println("commit/rollback");
String answer=br.readLine();
if(answer.equals("commit"))
{ con.commit();
}
if(answer.equals("rollback")){
con.rollback();
}
con.close();
19-04-2023 31
Statement st = con.createStatement ();
con.setAutoCommit(false);
st.executeUpdate("insert into college values
(‘olamipa’, ‘mumbai’, 1009)");
Savepoint svpt = con.setSavepoint ("mysp");
st.executeUpdate("update college set cname=
‘xavier’ where code=1001");
st.executeUpdate("insert into college values
(‘KIIT’, ‘Bhubaneswar’, 1008)");
con.rollback(svpt);
con.commit();

19-04-2023 32
Stored Procedure
• A stored procedure is a prepared SQL code
that you can save, so the code can be reused
over and over again.
• So if you have an SQL query that you write
over and over again, save it as a stored
procedure, and then just call it to execute it.
• You can also pass parameters to a stored
procedure, so that the stored procedure can
act based on the parameter value(s) that is
passed.
19-04-2023 33
Syntax
:
Create procedure <procedure_Name>
As
Begin
<SQL Statement>
End

19-04-2023 34
Example
CREATE PROCEDURE Selectstudent
AS
BEGIN
SELECT * FROM student
END

Exec Selectstudent

19-04-2023 35
Insert Query Example
CREATE PROCEDURE insertstudent
@rollno varchar(50), @name varchar(50),
@class varchar(50), @college
varchar(50)
AS
BEGIN
Insert into student(rollno, name, class, college)
Values(@rollno, @name, @class, @college)
END
19-04-2023 36
Execution of Insert Query Example
Exec insertstudent(10,’amit’,’cse’,’kec’);

19-04-2023 37
Update Query Example
CREATE PROCEDURE updatestudent
@rollno varchar(50), @name varchar(50),
@class varchar(50), @college
varchar(50)
AS
BEGIN
Update student set name=@name,
class=@class, college=@college where
rollno=@rollno
19-04-2023 38

END
Execution of Update Query
Example
Exec updatestudent(10,’sumit’,’IT’,’kec’);

19-04-2023 39
Delete Query Example
CREATE PROCEDURE deletestudent
@rollno varchar(50)
AS
BEGIN
Delete from student where rollno=@rollno
END

19-04-2023 40
Execution of Delete Query Example
Exec deletestudent(10);

19-04-2023 41
Select Query Example
CREATE PROCEDURE selectstudent
@rollno varchar(50)
AS
BEGIN
Select * from student where rollno=@rollno
END

19-04-2023 42
Execution of Delete Query Example
Exec selectstudent(10);

19-04-2023 43

You might also like