You are on page 1of 8

>>Hibernate Architecture (Java Database Connectivity), JTA (Java

The Hibernate architecture includes many Transaction API) and JNDI (Java Naming
objects such as persistent object, session Directory Interface).
factory, transaction factory, connection Elements of Hibernate Architecture
factory, session, transaction etc. SessionFactory
The Hibernate architecture is categorized in o The SessionFactory is a factory of
four layers. session and client of ConnectionProvider.
 Java application layer o It holds second level cache of data.
 Hibernate framework layer o The org.hibernate.SessionFactory
 Backhand API layer interface provides factory method to get
 Database layer the object of Session.
Diagram of hibernate architecture: Session
o The session object provides an interface
between the application and data stored
in the database.
o It is a short-lived object and wraps the
JDBC connection.
o It holds a first-level cache (mandatory)
of data.
o The org.hibernate.Session interface
provides methods to insert, update and
delete the object.
o It also provides factory methods for
Transaction, Query and Criteria.
Transaction
o The transaction object specifies the
atomic unit of work. It is optional.
Detailed view of the Hibernate Application
o The org.hibernate.Transaction interface
Architecture with important its core classes.
provides methods for transaction
management.
ConnectionProvider
o It is a factory of JDBC connections.
o It abstracts application from
DriverManager or DataSource. It is
optional.
TransactionFactory
o It is a factory of Transaction.

>>JDBC Drivers
Java Database Connectivity (JDBC) is an
application programming interface (API) for
the programming language Java, which defines
Hibernate framework uses many objects such
how a client may access any kind of tabular
as session factory, session, transaction etc.
data, especially relational database. It acts as
Alongwith existing Java API such as JDBC
a middle layer interface between java
applications and database. The JDBC classes data transferred through this driver is
are contained in the Java not so secured.
Package java.sql and javax.sql.  The ODBC bridge driver is needed to be
JDBC helps you to write Java applications installed in individual client machines.
that manage these three programming  Type-1 driver isn’t written in java, that’s
activities: why it isn’t a portable driver.
1. Connect to a data source, like a database.  This driver software is built-in with JDK
2. Send queries and update statements to so no need to install separately.
the database  It is a database independent driver.
3. Retrieve and process the results received Type-2 Driver (Native-API Driver)
from the database in answer to your The Native API driver uses the client -side
query libraries of the database. This driver
Structure of JDBC  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.
 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.
JDBC drivers are client-side adapters Type-3 driver (Network Protocol Driver)
(installed on the client machine, not on the
server) that convert requests from Java
programs to a protocol that the DBMS can
understand. There are 4 types of JDBC
drivers:
1. Type-1 driver JDBC-ODBC bridge driver
2. Type-2 driver Native-API driver
3. Type-3 driver Network Protocol driver
4. Type-4 driver Thin driver
Type-1 Driver (JDBC-ODBC Bridge Driver)
Type-1 driver or JDBC-ODBC bridge driver
uses ODBC driver to connect to the database.
The Network Protocol driver uses middleware
The JDBC-ODBC bridge driver converts
(application server) that converts JDBC calls
JDBC method calls into the ODBC function
directly or indirectly into the vendor-specific
calls. Type-1 driver is also called Universal
database protocol. Here all the database
driver because it can be used to connect to
connectivity drivers are present in a single
any of the databases.
server, hence no need of individual client-side
 As a common driver is used in order to
installation.
interact with different databases, the
 Type-3 drivers are fully written in Java,  Compilation
hence they are portable drivers.  Initialization
 No client side library is required because  Execution
of application server that can perform  Cleanup
many tasks like auditing, load balancing, The four phases have been described below −
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 another database.
Type-4 Driver (Thin Driver)

JSP Compilation
When a browser asks for a JSP, the JSP
engine first checks to see whether it needs
to compile the page. If the page has never
been compiled, or if the JSP has been
modified since it was last compiled, the JSP
engine compiles the page.
The compilation process involves three steps

 Parsing the JSP.
 Turning the JSP into a servlet.
 Compiling the servlet.
JSP Initialization
Type-4 driver is also called native protocol When a container loads a JSP it invokes
driver. This driver interact directly with the jspInit() method before servicing any
database. It does not require any native requests. If you need to perform JSP-
database library, that is why it is also known specific initialization, override
as Thin Driver. the jspInit() method −
 Does not require any native library and public void jspInit(){
Middleware server, so no client-side or // Initialization code...
server-side installation. }
 It is fully written in Java language, hence JSP Execution
they are portable drivers. This phase represents all interactions with
requests until the JSP is destroyed.
Whenever a browser requests a JSP and the
>>JSP Life Cycle page has been loaded and initialized, the JSP
A JSP life cycle is defined as the process engine invokes the _jspService() method in
from its creation till the destruction. the JSP.
Paths Followed By JSP void _jspService(HttpServletRequest
The following are the paths followed by a JSP request, HttpServletResponse response) {
// Service handling code...
}
The _jspService() method of a JSP is invoked
on request basis. This is responsible for
generating the response for that request and
this method is also responsible for generating
responses to all seven of the HTTP methods,
i.e. GET, POST, DELETE, etc.
JSP Cleanup
The destruction phase of the JSP life cycle
represents when a JSP is being removed from
use by a container.
The jspDestroy() method is the JSP
equivalent of the destroy method for The above diagram depicts the Model, View
servlets. Override jspDestroy when you need and Controller to the Struts2 high level
to perform any cleanup, such as releasing architecture. The controller is implemented
database connections or closing open files. with a Struts2 dispatch servlet filter as well
public void jspDestroy() {
as interceptors, this model is implemented
// Your cleanup code goes here.
with actions, and the view is a combination of
}
result types and results. The value stack and
OGNL provides common thread, linking and
enabling integration between the other
>>Struts 2 - Architecture
components.
From a high level, Struts2 is a pull-MVC (or
Apart from the above components, there will
MVC2) framework. The Model-ViewController
be a lot of information that relates to
pattern in Struts2 is implemented with the
configuration. Configuration for the web
following five core components −
application, as well as configuration for
 Actions
actions, interceptors, results, etc.
 Interceptors
This is the architectural overview of the
 Value Stack / OGNL
Struts 2 MVC pattern.
 Results / Result types
Request Life Cycle
 View technologies
Based on the above diagram, you can
Struts 2 is slightly different from a
understand the work flow through user's
traditional MVC framework, where the action
request life cycle in Struts 2 as follows −
takes the role of the model rather than the
 User sends a request to the server for
controller, although there is some overlap.
requesting for some resource (i.e. pages).
 The Filter Dispatcher looks at the
request and then determines appropriate
Action.
 Configured interceptor functionalities
applies such as validation, file upload etc.
 Selected action is performed based on
the requested operation.
 Again, configured interceptors are applied
to do any post-processing if required.
 Finally, the result is prepared by the view protected void Button_Click
and returns the result to the user. (objectsender, EventArgs e)
{
connection();
>>Login Authentication (Stored query = "EmpLogin";
Procedure) SqlCommand com = new SqlCommand(query, con);
First create one table named Emp_Login in com.CommandType =
the SQL database which looks as :  CommandType.StoredProcedure;
com.Parameters.AddWithValue("@usename",
TextBox1.Text.ToString()); // username 
com.Parameters.AddWithValue("@password",
TextBox2.Text.ToString()); // password
int usercount = (Int32)com.ExecuteScalar();
Insert the One Record in the table as: //for taking single value
Insert into Emp_Login if (usercount == 1)  // comparing users from table 
(username,password) values ('abc','xyz') {
Stored Procedure named EmpLogin Response.Redirect("Welcome.aspx");
Create  procedure EmpLogin //for sucsseful login
( }
@Usename Varchar (20), else
@password varchar (10) {
) con.Close();
as Label1.Text = "Invalid User Name or
Begin Password";  //for invalid login
Select COUNT(*) from EmpLogin where }
username=@usename and }
password=@password The most important part of the preceding
END code is the if condition part, integer variable
In the above Stored Procedure named user count is used to count the single value
EmpLogin the variable @usename is used for from the Stored Procedure using
the username and @password is used for the ExecuteScalar, if the records are found in
password. The select query counts the the table it returns 1 then the page is
number of users from the table whose name redirected to the Welcome page otherwise it
matches with the exact two variables; that is gives Invalid User.
@usename and @password which comes from
the front end user input page.
Loginapplication >>EJB Architecture
Then the  <form> section of the Default.aspx The EJB architecture consists of three main
page looks as in the following: components: enterprise beans (EJBs), the
EJB container, and the Java application
server. EJBs run inside an EJB container, and
the EJB container runs inside a Java
application server.
There are three types of EJB i.e. session
beans, message-driven beans and entity
beans.
 Session beans are invoked by the client
and make enterprise functionality such
as transactions and resource management  Singleton beans are like application scope
available to the client programmatically. in the Servlet API. A singleton session
 Message-driven beans also encapsulate bean exists only once for each client.
and deliver enterprise functionality, but >Thread Safety with Session Beans
they are asynchronous, and event driven. A stateful session bean can only be accessed
Message-driven beans listen and respond by one client at a time, so thread safety is
to events and cannot be invoked by the guaranteed when you're working with this
client. type of bean. Stateless session beans and
 Entity beans summarizes the state that singleton beans are more flexible, allowing
can be remained in the database. Now, it concurrent connections which is managed by
is replaced with JPA (Java Persistent developer.
API). >Message-Driven Beans
>EJB vs JavaBeans Message-driven beans (MDBs) are invoked
Enterprise JavaBeans was the first via JMS (Java Message Service) messages.
component-based development model for Java JMS works like a distributed Command
EE. EJB is similar to JavaBeans in being pattern, where the message-driven bean acts
component based, but that's where the as the listener for the command. When a
similarity ends: message arrives on a topic or queue, the
 A JavaBean is a Java class that message-driven bean listening on that topic is
encapsulates multiple objects and invoked.
conforms to certain conventions. Message-driven beans are not as commonly
JavaBeans are used mainly for client-side used as session beans, but they are powerful.
development. Being asynchronous and event-driven, they're
 An enterprise bean (EJB) is a Java class especially useful for long-running jobs where
with specific server-side capabilities. it's important to conserve resources.
Enterprise beans are used in large-scale The simplest architecture would consist of
business applications and systems. the EJB application and its container and
>Session Beans server, which coordinate with the message
A session bean is the most generic type of service processing the MDBs.
enterprise bean, representing a chunk of
business functionality that can be called by a
client. The client in this case could be another
class in the local JVM or a remote call.
The EJB container manages the session bean
lifecycle, which is determined by the bean's Diagram of an MDB architecture
state: Working with message-driven beans is more
 Stateless session beans are similar to involved than using session beans. In an event-
the request scope in the Java Servlet driven environment you'll typically need
API. Stateless session beans contain a a message broker like ActiveMQ.
chunk of callable functionality but are >EJB annotations
otherwise stateless. Annotations make it very easy to configure
 Stateful session beans are associated enterprise beans for a wide range of
with one client only and attach to that functionality found in Java EE.
client's ongoing session. Stateful session @Stateless Annotation example
beans function similarly to the session import javax.ejb.Stateless;
scope in the Servlet API. @Stateless
public class MyStatelessBean { PreparedStatement pstmt =
public String getGreeting() { con.prepareStatement("INSERT INTO
return "Hello JavaWorld."; MyTable VALUES(?, ?)");
} Step 3: Set values to the place holders
} Set the values to the place holders using the
This stateless bean contains a simple setter methods of the PreparedStatement
signature that takes no arguments and interface. Chose the methods according to
returns a string. Don't let simplicity fool you, the datatype of the column.
though: this bean can do anything you need it And if it is of Blob type you can set value to it
to, including interacting with other beans, using the setBinaryStream() or setBlob()
services, or your application's data layer. methods.
@EJB annotation example pstmt.setString(1, "sample image");
public class MyServlet extends //Inserting Blob type
HttpServlet { InputStream in = new FileInputStream
@EJB ("E:\\images\\image.jpg");
MyStatelessBean myEjb; pstmt.setBlob(2, in);
public void doGet(HttpServletRequest Step 4: Execute the statement
request, HttpServletResponse response){ import java.io.FileInputStream;
response.getWriter().write("EJB Says " + import java.io.InputStream;
testStatelessEjb.getGreeting()); import java.sql.Connection;
}} import java.sql.DriverManager;
Here, we inject the stateless bean into a import java.sql.PreparedStatement;
servlet, and then it's available for use. public class InsertImageToMySqlDB {
public static void main(String args[])
throws Exception{
>>Insert Image into Database Java
      //Registering the Driver
To hold an image in MySQL database
DriverManager.registerDriver(new
generally blob type is used. com.mysql.jdbc.Driver());
Step 1: Connect to the database //Getting the connection
You can connect to a database using String mysqlUrl =
the getConnection() method "jdbc:mysql://localhost/sampleDB";
Connect to the MySQL database by passing Connection con =
the MySQL URL which is DriverManager.getConnection(mysqlUrl,
jdbc:mysql://localhost/sampleDB (sampleDB "root", "password");
System.out.println("Connection
is the database name), username and
established ......");
password as parameters to the
PreparedStatement pstmt =
getConnection() method. con.prepareStatement("INSERT INTO
String mysqlUrl = MyTable VALUES(?,?)");
"jdbc:mysql://localhost/sampleDB"; pstmt.setString(1, "sample image");
Connection con = //Inserting Blob type
DriverManager.getConnection(mysqlUrl, InputStream in = new
"root", "password"); FileInputStream("E:\\images\\cat.jpg");
Step 2: Create a Prepared statement pstmt.setBlob(2, in);
Create a PreparedStatement object using //Executing the statement
the prepareStatement() method of the pstmt.execute();
Connection interface. To this method pass System.out.println("Record inserted......");
the insert query (with place holders) as a    }
parameter. }

You might also like