Sunday, 10 July 2022

JDBC - Java Database Connectivity

 


Learn Full Advacnce  Java Course
   https://youtube.com/playlist?list=PLkx9f4H3tJMI4735IyPUp88bKCvatY2IY

JAVA DATABASE CONNECTIVITY

Introduction of JDBC

JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code.

JDBC stands for “Java Database Connectivity”. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the database from Java code using a  set  of  standard  interfaces  and classes written in the Java programming language. The database that we want to connect must follow the ANSI SQL-2 standard.


JDBC Architecture

JDBC is a software abstraction sitting between your application and the database you want to access.

The application layer provides GUIs, business logic etc. and is written in Java.

JDBC layer  provides API calls to access different types of databases which the application layer   can use.


Database Drivers

JavaSoft develops the JDBC API. JavaSoft has divided JDBC driver into four categories, based on their  construction  and the type of database they are intended to support. To connect with individual databases, JDBC (the Java Database Connectivity API) requires drivers for each database. The JDBC driver gives out the connection to the database and implements the protocol for transferring the query and result between client and database.

These four categories are explained below.

§ Type 1: JDBC-ODBC Bridge Driver

§ Type 2: Native-API Driver

§ Type 3: Network Protocol Driver

§ Type 4: Native Protocol Driver


JDBC-ODBC Bridge Driver

The JDBC Type 1 driver is also known as the JDBC-ODBC Bridge. This driver is an implementation of the lower-level JDBC Driver API that makes use of the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC (Open Database Connectivity) calls and sends them to the ODBC driver. This implies that the ODBC driver, as well as the client database code, installed on the client machine.

The Type 1 Driver makes use of ODBC which in turn depends on native libraries of the underlying operating system which makes it platform-dependent. This makes any application that uses this driver non-portable as the ODBC driver for the specific operating system is required in the client machine. The database must also support the ODBC drivers for the Type 1 Driver to make a connection.

The bridge is usually used when there is no pure-Java driver available for a particular database.

Advantages

The following are the advantages of the Type 1 Driver:

§ Connectivity to most databases is possible as most databases contain ODBC drivers.

§ Installation of the Type 1 driver is very easy.

Disadvantages

The following are the disadvantages of the Type 1 Driver:

§ The Type 1 Driver is partially written in Java which makes it not portable.

§ The Type 1 Driver is not suitable for Internet Applications (Web Applications)

§ The Type 1 Driver contains a performance overhead as JDBC calls is converted into ODBC calls and then passed on to the ODBC driver.

Native-API Driver

The JDBC Type 2 driver is also known as the Native-API Driver. This driver is an implementation of the lower-level JDBC Driver API that makes use of the client-side libraries of the database to connect. The driver converts JDBC calls into database-specific calls on the client API for databases such as SQL Server, Informix, DB2, Oracle, or Sybase. The Type 2 driver communicates directly with the database server; therefore this style of driver requires that some binary code be loaded on each client machine.

Advantages

The following are the advantages of the Type 2 Driver:

§ The Type 2 Driver is better than the JDBC-ODBC bridge driver, since no ODBC  drivers  are  required.

Disadvantages

The following are the disadvantages of the Type 2 Driver:

§ The client API libraries of the specific database vendor must be installed on the client machine.

§ Not all the database vendors provide client API libraries.

§ The Type 2 Driver is not suitable for Internet Applications (Web Applications)


Network Protocol Driver

The JDBC Type 3 driver is also known as the Pure Java Driver for database Middleware. The JDBC Type 3 driver follows a three-tiered approach where the client code sends the JDBC calls through the network to a middle-tier server. The middle-tier converts the the JDBC calls directly or indirectly into database specific protocol, which will forward the JDBC calls to the database. The conversion logic that translates the JDBC calls resides in the middle-tier, and not in the client side like that of the JDBC Type 4 driver.

Advantages

The following are the advantages of the Type 3 Driver:

§ The translation of the JDBC calls resides on the middle-tier and therefore no database library is required on the client side.

§ On the client side only the JDBC Type 3 driver is required, and any database can be supported, as long as the middle-tier supports the database.

§ The middle-tier which implements the JDBC Type 3 driver can provide additional services like caching, auditing ...

Disadvantages

The following are the disadvantages of the Type 3 Driver:

§ The additional layer might be a bottleneck for the JDBC calls.

Native Protocol Driver

The JDBC Type 4 driver is also known as the Direct to Database Pure Java Driver. The JDBC Type  4 driver converts the JDBC calls directly into database specific calls which mean the client can directly communicate with the database management system (DBMS). The Type 4 drivers are completely written in Java and are therefore platform independent. The Type 4 driver is installed in client side and runs within the Java Virtual Machine.

Advantages

The following are the advantages of the Type 4 Driver:

§ The Type 4 driver is platform independent and therefore easy to deploy to different client environments.

§ The performance of Type 4 drivers is higher as the driver does not need to convert the JDBC calls into ODBC or to Middleware Type drivers.

Disadvantages

The following are the disadvantages of the Type 4 Driver:

§ A vendor-specific driver is required for each of the databases the client whishes to connect.




__________________________________________________

JDBC APIs for database Connectivity (Java.sql Package)




The JDBC 3.0 API includes the entire API in the java.sql package and the javax.sql package. The JDBC API is a Java API for accessing virtually any kind of tabular data. The JDBC API consists of    a set of classes and interfaces written in the Java programming language that provide a standard  API for tool/database developers and makes it possible to write industrial-strength database applications entirely in the Java programming language.

The JDBC API makes it easy to send SQL statements to relational database systems and supports  all dialects of SQL. But the JDBC API goes beyond SQL,

also making it possible to interact with other kinds of data sources, such as files containing tabular data.

In simplest terms, a JDBC technology-based driver ("JDBC driver") makes it possible to do three things:

1.     Establish a connection with a data source

2.    Send queries and update statements to the data source

3.    Process the results

In order to connect any application or an applet to a database there are various classes and interfaces are available in the java.sql package. Depending on the requirements these classes and interfaces can be used.

Some of the classes and interfaces which are used  to perform various database tasks.

java.sql.Connection

This interface abstracts most of the interaction with the database. In order to send SQL statements to the database and to read the results a connection is used. It is also used   to connect with the database.

java.sql.Driver

This is an interface that abstracts the vendor specific connection protocol. Implementations of this interface can

be found from database vendors as well as third party database driver vendors.

java.sql.DriverManager

This class provides the functionality necessary for managing one or more database drivers. Each driver in turn lets you to connect to a specific database.

java.sql.CallableStatement


This interface can be used to execute stored procedures.

java.sql.PreparedStatement

This is a variant of the java.sql.Statement interface allowing for parameterized SQL statements.

java.sql.ResultSet

This interface abstracts results of executing SQL SELECT statements. This interface provides methods to access the result row-by-row.

java.sql.statement

This interface lets you to execute SQL statements over the underlying connection and access the results.

Connection Interface

This interface is available in the java.sql package. The connection interface is used to establish a connection to the database you want to access. The Connection interface defines following  methods:

§ void close()

This method frees the Connection object’s database and other JDBC resources.

§    void commit()

This method makes all the changes made since the last commit or rollback permanent. It throws SQLException.

§ Statement createStatement()

This method creates a Statement object for sending SQL statements to the database. It throws SQLException.

§ Boolean isClosed()

This methods returns true if the connection is close else returns false.

§ CallableStatement prepareCall(String s)

This   method   creates   a   CallableStatement   object   for   calling  stored  procedures.                      It throws SQLException.

§ PreparedStatement prepareStatement(String s)

This method creates a PreparedStatement object for sending SQL statements with or without IN parameter. It throws SQLException.

§ void rollback()

This method undoes all changes made to the database.

Statement Interface

The Statement object is created for executing static SQL statements. To execute SQL Statements, Statement is the simple and easy.

The Statement interface has several methods which can be used to execute SQL statement.

§ void close()

This method releases the statement object’s database and JDBC resources.

§ boolean execute(String s)

This method executes the SQL statement specified by s.  The  getResultSet()  method  is  used  to  retrieve the result.

§ ResultSet executeQuery(String s)

This method executed the SQL statement specified by s and returns the ResultSet object.

§ int executeUpdate(String s)

This    method    executes    the    SQL    statement    specified    by    s.              These statements may be INSERT,UPDATE or DELETE.

§ int getMaxRows()

This method returns the maximum number of rows that  are  generated  by  the  executeQuery()  method.

§ ResultSet getResultSet()

This method retrives the ResultSet generated by the execute() method.

Prepared statement

The Prepared Statement object can be used to execute a dynamic SQL statement with IN  parameter. A Prepared Statement can be precompiled and used repeatedly. This interface has methods to handle PreparedStatement objects. The PreparedStatement object is created using PreparedStatement() method in Connection class.

§ Boolean execute()

This method executes the SQL statement in this object. The getResult() method is used to retrieve the result.

§ ResultSet executeQuery()

This method is used to execute SQL statements in this object. It returns the ResultSet object.

§ Int executeUpdate()

This method executes the SQL statement in this object. The SQL statement  must  be  an  SQL insert, update and delete statement.

§   ResultSetMetaData getMetaData()

This method retrieves a ResultSetMetaData object that contains information about the columns of the ResultSet object that will be returned when this object is executed.

§ IN Parameter:

§ An IN parameter is used to execute a dynamic SQL statement.


§  In some certain conditions where in we need to pass different values to an SQL  statement, then  such values can be specified by using ? in the SQL statement.

§ The actual values can be passed using the setXXX() method at the time of execution.

§ The “ ? “ in a Java SQL statement stands for an input parameter to be supplied after using setXXX method().

§ E.g.

PreparedStatement st = cnmain.prepareStatement(“Select * from emp where empno=?”); St.setInt(1,1002);

ResultSet rs= st.executeQuery();

S

The general form for setting the IN parameter is as : setXXX(integer, value)

Where xxx is the value type which may be int, float, Boolean etc... Integer is the position of IN parameter in the SQL statement. Value is the value that is to be supplied in place of ?.

Callable statement

§ A callable statement object is used to execute stored procedures defined in the RDBMS.

§ A procedure with OUT parameter can be executed only in this Callable Statement.

§ A callable statement can also contain IN parameter.

§ An OUT parameter has to be registered prior to executing the stored procedure.

§ An OUT parameter in the stored procedure is represented by (?).

§ An OUT parameter is  registered  using  the  registerOutParameter()  method.  This  method  declares what type of the OUT parameter is.

§ After the CallableStatement is executed, the OUT parameter are to be obtained using the getXXX() method.

§ The general form of registering OUT parameters other than NUMERIC and DECIMAL VALUES is as under :

registerOutParameter(int index, Type type)

where indx is the relative position of the OUT parameter in the SQL. Type is the SQL data type of OUT parameter.

§ E.g.

CallableStatement cstmt = con.prepareCall(EXECUTE ADD_REC(?,?,?));

There are three parameters. Let us assume that first two are IN parameters and the last one is the OUT parameter. The IN and OUT parameters are defined as under :

st.setInt(1,1001); st.setString(2,”Kamal”);

st.registerOutParameter(3,Types.LONGVARCHAR);

The CallableStatement is executed by calling the execute methods.

ResultSet rs = st.executeQuery();

The registered OUT parameter can be retrieved using getXXX() method in the CallableStatement interface.

§ BigDecimal getBigDecimal(int index)

This method retrieves the OUT parameters of JDBC NUMERIC type at the specified index.

§ byte getByte(int index)

This method retrieves the OUT parameter of JDBC NUMERIC type at the specified index location.

§ date getDate(int index)

This method retrieves the OUT parameter of JDBC DATE type at the specified index column.

§ double getDouble(int index)

This method retrieves the OUT parameter of JDBC DOUBLE type at the specified index column.

§ float getFloat(int index)

This method retrieves the OUT parameter of JDBC FLOAT type at the specified index column.

Result set

The executeQuery() and getResultSet() when called on Statement, PreparedStatement, and CallableStatement it returns the object of  type ResultSet. The ResultSet object contains results  after the execution of SQL statement. The ResultSet object maintains a cursor pointing to the current row of results. The next() method moves cursor to the next row of the result set. The ResultSet interface has many methods to get the results from the result set.

§ boolean absolute(int row)

This method moves the cursor to the specified row numer in the result set.

§ void afterLast()

This method moves the crsor to the end of the result set just after the last row.

§ void close()

This method releases the object’s database.

§ void deleteRow()

This method deletes the current row of this result set.

§ boolean first()

This method moves the cursor to the first row of the result set.

§ BigDecimal getBigDecimal(int index)

This method retrieves the value of the specified column as BigDecimal.

§ boolean getBoolean(int index)

This method retrieves the value of the specified column as Boolean.


§ boolean getBoolean(String clName)

This method retrieves the name of the specified column as Boolean.

§ byte getByte(int index)

This method retrieves the value of the specified column as byte.

§ date getDate(int index)

This method retrieves the value of the specified column as date.

§ float getFloat(int index)

This method retrieves the value of the specified column as float.

§ ResultSetMetaData getMetaData()

This method returns properties of the ResultSet object.

§ int getRow()

This method returns the current row number.

§ Statement getStatement()

This method returns the object which produced the ResultSet.

§ String getString(int index)

This method returns the object which produced the ResultSet.

§ boolean isFirst()

This method checks whether the cursor is in first row.

§ boolean isLast()

This method checks whether the cursor is in last row.

§ boolean next()

This method checks whether the cursor is in next row.

§ boolean previous()

This method checks whether the cursor is in previous row.



______________________________________________

Steps of JDBC URL for MS-Access database

1)       Go to Control Panel.

2)      Click on Administrative Tools.

3)      Click on Data Sources (ODBC).

4)      Select MS-Access database and then click on Add.

5)      Select Microsoft Access Driver (*.mdb).

6)      Click over the FINISH.

7)      It will display ODBC Microsoft Access Setup Dialog box.

8)      In this dialog box, type the name of the data source.

9)      Then click on Select in the Database frame.

10)   It will display "Select Database" dialog box.

11)    Select the database and click on the ok. ODBC data source is created.

__________________________________________________________

JDBC steps for ODBC Database Connection

Here are the basic steps to connect Java program to MySQL using JDBC APIs

1.      Importing required classes

Import java.sql package.

2.      Loading the Driver

In the second step of jdbc connection  process,  we  load  the  driver  by  calling  Class.forName()  method. A client can connect to Database server by JDBC driver

The call is made as given below: Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);

1.      Creating JDBC Connection to database

§ In order to create a connection, the loading of JDBC database driver does not connect to the database.

§ Before executing any SQL statement it is mandatory to establish a connection with a database.

§ To do this the getConnection() method of  the DriverManager  class is to be  invoked which is  used to  find a specific driver that can create a connection to the URL requested.

§ Here, the DriverManager class searches for the registered drivers which can process the database.

If a driver is not found then an exception is thrown.

§ The call to the getConnection() method is as given below.

Connection con = Drivermanager.getConnection(“jdbc:odbc:dbname”,“ ”, “ ” );

Here, the getConnection() method takes three arguments, the first is  the string   type argument  that      is the URL for the database. The second argument is username and the third  argument  is  the  password.

2.      Creating statement object

§ In order to interact with the database, the SQL statements must be executed.

§ This requires that a Statement object needs to be created to manage the SQL statements.

§ To do this the createStatement() method of the Connection class is to be invoked.

§ Statement st = con.createStatement();

§ The above statement creates a Statement object using the database connection.

§   The Statement class provides methods for executing SQL statements and retrieving the results   from the statements execution.


3.      Executing statement object

§ The SQL statement can be executed by invoking the executeQuery() method.

String query =”select * from emp”; ResultSet rs = st.executeQuery(query);

§ The above statement sends the query to the database and returns the results of the query as a ResultSet.

§ If there are any errors during the execution of the query then an exception is thrown.

4.      Manipulating ResultSet

§ The last step is to iterate the ResultSet.

§ A ResultSet is a collection of results retrieved from a query.

§ There are various methods available in the ResultSet class to iterate through these results.  One of  the method is next() which places the pointer to the next record. This method returns a Boolean value. If this value is true then it indicates that there is data to fetch.

§ A while loop can be used to fetch rows from a ResultSet.

§ rs.next() is used in the while loop for the iterating.

MS-Access Example

import java.sql.*; class select

{

public static void main(String args[])

{


try

{


 

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:odbc:student"); Statement st = con.createStatement();

String query = "select * from tblStudent"; ResultSet rs = st.executeQuery(query); while(rs.next())

{

                    //youtube.com/avadhtutor

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

int rollno = rs.getInt("rollno"); String name = rs.getString("name");

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

 

System.out.println(id +" "+rollno +" "+name +" "+course);

}

}

catch(Exception e)

{

System.out.println(e);

}

}

}



___________________________________________________

JDBC steps for other Database Connection

1.      Load the JDBC driver

To load a driver, you specify the class name of the database driver in the Class.forName method.    By doing so, you automatically create a driver instance and register it with the JDBC driver manager.

try

{

Class.forName ("connect.microsoft.MicrosoftDriver"); Class.forName ("oracle.jdbc.driver.OracleDriver"); Class.forName ("com.sybase.jdbc.SybDriver");

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

}

catch (ClassNotFoundException cnfe)

{

System.err.println ("Error loading driver: " + cnfe);

}

 

 

2.      Define the connection URL

In JDBC, a connection URL specifies the server host, port, and database name with which to establish a connection.

String host =  "localhost"; String dbName = "someName"; int port = 3306;

§ String oracleURL = "jdbc:oracle:thin:@" + host +":" + port + ":" + dbName;


§ String sybaseURL = "jdbc:sybase:Tds:" + host +":" + port + ":" + "?SERVICENAME=" + dbName;

§ String msAccessURL = "jdbc:odbc:" + dbName;

§ String mySqlURL = "jdbc:mysql://"+host+":"+port+"/"+dbName+"";

3.      Establish the connection

With the connection URL, username, and password, a network connection to the database can be established. Once the connection is established, database queries can be performed until the connection is closed.

String username = "root"; String password = "admin";

Connection connection =DriverManager.getConnection(mySqlURL, username, password);

4.      Create a Statement object

Creating a Statement object enables you to send queries and commands to the database. Statement statement = connection.createStatement();

5.      Execute a query or update

Given a Statement object, you can send SQL statements to the database by using the execute, executeQuery, executeUpdate.

String query = "SELECT col1, col2, col3 FROM sometable"; ResultSet resultSet = statement.executeQuery(query);

§ executeQuery

§   Executes an SQL query and returns the data in a ResultSet. The ResultSet may be empty, but    never null.

§ executeUpdate.

Used for UPDATE, INSERT, or DELETE commands. Returns the number  of  rows  affected,  which could be zero. Also provides support for Data Definition Language (DDL) commands, for example, CREATE TABLE, DROP TABLE, and ALTER TABLE.

6.      Process the results

When a database query is executed, a ResultSet is returned. The ResultSet represents a set of rows      and columns that you can process by calls  to  next  and  various  getXxx methods. while(resultSet.next())

{

System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + " " + resultSet.getString("firstname")    +    "     " resultSet.getString("lastname"));

}

We suggest that when you access the columns of a ResultSet, you use the column name instead of the column index. That way, if the column structure of the table changes, the code interacting with the ResultSet will be less likely to fail.

7.      Close the connection

When you are finished performing queries and processing results, you should close the connection, releasing resources to the database.

connection.close ();

Meta Data

The term "meta" here means information about your data that  does not interest the end users at  all, but which you need to know in order to handle the data. JDBC provides two meta-data classes: java.sql.ResultSetMetaData and java.sql.DatabaseMetaData. The meta-data described by these classes was included in the original JDBC ResultSet and Connection classes.

Result Set Meta Data

As its name implies, the ResultSetMetaData class provides extra information about ResultSet objects returned from a database query. In the embedded queries you made earlier in the book,    you hardcoded into your queries much of the information a ResultSetMetaData object gives you. This class provides you with answers to the following questions:

§ How many columns are in the result set?

§ Are column names case-sensitive?

§ Can you search on a given column?

§ Is NULL a valid value for a given column?

§ How many characters is the maximum display size for a given column?

§ What label should be used in a display header for the column?

§ What is the name of a given column?

§ What table did a given column come from?

§ What is the datatype of a given column?

Methods of Resultset Metadata:

§ getColumnCount()

Returns the number of columns in this ResultSet object.

§ getColumnName(int column)

Get the designated column’s name.


§ getColumnType(in column)

Retrieves the designated column’s SQL type.

§ getSchemaName(int column)

Get the designated column’s table’s schema.

§ getTableName(int column)

Get the designated column’s table name.

§ isAutoIncrement(int column)

Indicateds whether the designated column is automatically numbered, thus read-only.

§ isCaseSensitive(int column)

Indicates whether a column’s case matters.

§ isCurrency(int column)

Indicates whether the designated column is a cash value.

§ isNullable(int column)

Indicated the nullability of values in the designated column.

§ isReadonly(int column)

Indicates whether the designated column is definitely not writable.

Database Meta Data

As the ResultSetMetaData class relates to the ResultSet class, the DatabaseMetaData  class relates to the Connection class (in spite of the naming inconsistency). The DatabaseMetaData class provides methods that tell you about the database for a given Connection object, including:

§ What tables exist in the database visible to the user?

§ What username is being used by this connection?

§ Is this database connection read-only?

§ What keywords are used by the database that are not SQL2?

§ Does the database support column aliasing?

§ Are multiple result sets from a single execute () call supported?

§ Are outer joins supported?

§ What are the primary keys for a table?

Methods name:

§ getDatabaseProductName( )

Returns the product name. i.e. the name of the database program.

§ getDatabaseProdouctVersion( )

Returns the version of the database program.

§ getDriverName( )

Returns the type of the JDBC driver.

§ getUserName( )

Returns the current user name.

§ getCatalogs( )

Returns the name of the database file or database.




________________________________________________________________

JDBC Data Types

JDBC/Java

SQL

JDBC/Java

java.lang.String

DOUBLE

double

java.lang.String

VARBINARY

byte[ ]

java.lang.String

BINARY

byte[ ]

Boolean

DATE

java.sql.Date

java.math.BigDecimal

TIME

java.sql.Time

Byte

TIMESTAMP

java.sql.Timestamp

Short

CLOB

java.sql.Clob

Int

BLOB

java.sql.Blob

Long

ARRAY

java.sql.Array


________________________________________________________

Database Exception Handling

getErrorCode( )

Gets the error number associated with the exception.

 

getMessage( )

Gets the JDBC driver's error message for an error, handled by the driver or gets the Oracle error number and message for a database error.

 

 

getSQLState( )

Gets the XOPEN SQLstate string. For a JDBC driver error, no useful information is returned from this method. For a database error, the five-digit XOPEN SQLstate code is returned. This method can return null.

getNextException( )

Gets the next Exception object in the exception chain.






Learn Full Advacnce  Java Course
   https://youtube.com/playlist?list=PLkx9f4H3tJMI4735IyPUp88bKCvatY2IY














Sunday, 19 June 2022

Types of Container in Java

 

Types of Container :

There are four basic containers in J2EE. In that two server  containers  and two client  containers are listed below.

Applet Container

Applet container is a client container which is used to manage an execution of the applet on the browser.

1)       Application Container.

Application container is a client container which is used to manage application client and their components.

2)      EJB Container.

EJB container is a server container which is used to manage Enterprise beans components.

3)      Web Container.

Web container is also a server container which is used to manage execution of JSP pages and servlet components.

Introduction to J2EE APIS

 


(Servlet, JSP, EJB, JMS, JavaMail, JSF, JNDI)


1)       Java Servlet :The Java Servlets provides object oriented abstractions for building dynamic web applications. Servlets are server side components that are a platform independent high  performance  replacement for CGI. Like CGI, Servlets dynamically generate HEML as a result  of  a  HTTP request.

2)      Java Server Pages [JSP]

The Java Server Pages are an extension of the Servlet API that simplifies the generation of dynamic web pages by providing template driven web application development. It uses XML/HTML like tags and Java Scrip lets to encapsulate the logic required to generate pages in a platform independent way.

3)      Enterprise Java Beans [EJB]

Enterprise Java Beans are a distributed component based framework. It provides  a  standard means of defining server-side components, and specifies a run-time environment for hosting the components on the server side. There are 3 main types of EJBs : Session beans, Entity beans and Message driven beans.

4)      Java Database Connectivity :

JDBC provides platform and vendor independent access to SQL compliant databases. Basic JDBC (version 2.0) is J2SE. The J2EE platform requires, besides the basic APIs, also the JDBC 2.0 Optional Package. JDBC allows transactional querying, retrieval and manipulation of data in a JDBC drivers or you can use a ODBC-to-JDBC bridge. This means that almost every relational database available can be used on J2EE platform.

5)      Java Message Service (JMS) :

JMS provides a Java API for message queuing, and publish and subscribe types of message- oriented middleware (MOM). This API is to use if applications in a distributed environment cannot be connected all the time and the handling of the communication should be a synchronous.

6)      Java Mail :

This API provides a platform independent and protocol independent framework to build Java  based email applications. Although platform independent, Java Mail depends on an underlying email server like Send Mail or MS Exchange Server for the actual sending of an email. It uses IMAP4, POP3 and SMTP as its underlying transport mechanisms.

7)      Java Beans Activation Framework (JAF) :

The Java Beans Activation Framework is required for Java Mail. Java Mail uses JAF to determine the contents of a Multiple Internet Main Extension (MIME) message and what appropriate actions can be done accordingly.

8)      Java Naming and Directory Interface (JNDI) :

JNDI standardizes access to different types of naming services. The API is designed to be independent of any specific naming or directory service implementation.  J2SE also specifies a  JNDI service provider interface (SPI) for naming and directory service providers to implement. JNDI is not a J2EE API but a J2SE API.

9)      Java Transaction API (JTA) :

This API is for implementing distributed transactional applications.

10)   The Java Connector Architecture (JCA) :

This API has recently been included in J2EE, and provides a means to integrate J2EE application components to legacy information systems.


Sunday, 12 June 2022

Enterprise Architecture styles In Java

 

Enterprise Architecture styles

Before we look into J2EE architecture, it is necessary to consider the architectural styles of contemporary distributed applications – 2-tier, 3-tier, and n-tier architecture. The purpose of this section is mainly to enable the reader to recognize the scope of and place for these patterns.

Typically client-server systems are based on the 2-tier architecture, where there is a clear  separation between the data and the presentation/business logic. Such systems are generally data-driven with the server most of time being database server, and the client being a graphical  user interface to operate on data. While this approach allows us to share data  across  the  enterprise, it does have many drawbacks.

Single-Tier Architecture

Simple software applications are written to run on a single computer. User inputs its verification, business logic and data accessed all these could be found together on single computer, this kind of architecture is called

Single Tier Architecture.

Because of all logic application services, the presentation, business rules and  the  data  access  layers exist in a single computing layer.

Advantage:

Single tier system is relatively easy to manage  and data consistency is  simple because data is  stored at only one single location.

Disadvantage:



Single storage location is not sufficient because of the changing business needs. With the single tier application we cannot share the data in the large amount; it can also not handle multiple users.

Two-Tier Architecture

§ Application  which  is  divided  into  two separate tires, client machine and database server machine is called as Two – Tier architecture application.

§ The application includes the presentation and business  logic.  Data  is  accessed  by  connecting client machine to a database which is lying on another machine.

Thin Client :

With the two tier architecture, if the presentation manager resides only with the client tier then the client is called as thin client. Other presentation logic, application logic, business logic, data logic and database manager reside with the server side.

Thick Client :

Server

Client

Request

Presentation Logic

Presentation Manager

Application

Business Logic

Database Logic

Database Manager

 

With the two tiers architecture if the presentation manager,  presentation logic, application logic reside with the client tier then the client is  called  as thick client. Others like business logic, data logic and database manager reside

with the server side.

Normal Client :

With the two tires architecture if the presentation manager and presentation logic reside with the client tier then the client is called as normal client. Others like application logic, business logic,

data logic and database manager reside with the server side.

Advantages :

Any changes made in data access logic will not  affect the presentation and business logic.  With   the two tier architecture it is easy to develop an application.

Disadvantages :

One of the disadvantages of Two – tier architecture is that the application is expected to support a limited number of users. The reason is that each client requires its own connection  and  each  connection requires CPU and memory. As the number of connections increases, the database performance degrades.

§ Another typical problem with a 2-tired approach is that of maintenance

§ Even the smallest of changes to an application might involve a complete rollout to the entire user base.


§ Even if it’s possible to automate the process, you are still faced with updating every single client installation.

Three Tier Architecture

Client

Server

Presentation                                                                    Database

Logic

Logic

Business Logic

§ In 3-tier Architecture an application is broken up into three separate logical layers, each with a well-defined set of interfaces.

§ The first tier is referred to as  presentation  layer and typically consists of a  graphical  user interface of some kind.

§ The middle tier, or business layer consists of the application or business logic.

§ And the third tier –  the  data layer    contains the data that is needed for the application

§ The middle tier (application logic ) is basically the code  that  the  user  calls  upon  to  retrieve  the  desired data.

§ The presentation layer then receives the data and formats it for display.

§  This separation of application logic from the user interface adds enormous flexibility to the design   of the application.

§ Multiple user interfaces can be built and deployed without ever changing the application logic, provided the application logic presents a clearly defined interface to the presentation layer.

§ J2EE provides several abstractions to meet the needs of each of these tiers.

§ The third tier contains the data that is needed for the application.

§ This data can consist of any source of information,  including  an  enterprise  database  such  as  oracle or Sybase, a set of XML documents, or even a directory service.

§ In addition to the traditional relational database storage mechanism, there are many different sources of enterprise data that your applications can access.

Advantages :

It improves scalability since the application servers can  be  deployed  on  many  machines.  The  database no longer requires a connection from every client – it only requires  connections  from  a smaller number of application servers. It provides better reusability  because  client  does  not  have direct access to the database.

Disadvantage :

It increases the complexity because to develop the three tier application is more difficult than developing a two tier applications.

N-Tier Architecture

As the title suggests, there is no hard  and  fast way to define the application layers for an n-tier system.

In fact, this kind of system can support a number of different configurations.

In an n-tier architecture the application logic is logically divided by function, rather than physically.

§  A  user  interface  that  handles  the  user’s interaction with the application – this  can  be  a  web browser  running  through  a  firewall,  a  heavier desktop application, or even a wireless device.

§ Presentation logic that defines what the user interface displays and how a user’s requests are handled. Depending on what user interfaces are supported, you may need  to  have  slightly  different versions of the presentation logic to handle the client appropriately.

§ Business logic that models the application’s business rules, often through interaction with the application’s data.

§ Infrastructure services that provide additional functionality required by the  application  components, such as messaging, transactional support.

§ The data layer where the enterprise’s data resides.

Advantages :

§   Separation  of  user  interface  logic  and  business  logic is done.                Business logic resides on small number of centralized machines (may be just one).

§ Easy to maintain, to manage, to scale, loosely coupled etc.

§ Additional features can be easily added.

Disadvantages :

§ It is having more complex structures and difficult to setup and maintain all the separated layers.

 

Introduction of J2EE (Advance Java)

 

An Introduction to J2EE

J2EE is Java, optimized for enterprise computing. Officially J2EE stands for Java 2 Platform, Enterprise Edition. Unlike the traditional Java, which is often used to build client enhancements, J2EE is designed to build server applications. Officially, the J2EE platform is "a set of coordinated specifications and practices that together enable solutions for developing, deploying,  and managing" such server applications.

As an enterprise platform, the J2EE environment extends basic Java with tools that "provide a complete, stable, secure, and fast Java platform to the enterprise level."

One goal often stated by developers is that by using J2EE, they're reducing  the  cost  and  complexity of creating large-scale solutions. Because Java is a strongly typed language meaning  that it requires data types to be used as specified, use of the language is often inherently more secure in Web applications than Web applications built with less strong typing such as C or even PHP and Perl.

Enterprise Architecture

The economy and technology of today have intensified the need for faster, more efficient, and larger-scale information management solutions. The J2EE specification  satisfies these challenges by providing a programming model that improves development productivity, standardizes the platform for hosting enterprise applications, and ensures portability of developed applications with an extensive test suite.

The J2EE platform uses a multitiered distributed application model for both enterprise applications. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application  component belongs. Following figure shows two multitiered J2EE applications divided into the tiers described in the following list.

§ Client-tier components run on the client machine.

§ Web-tier components run on the J2EE server.

§ Business-tier components run on the J2EE server.

§  Enterprise information system (EIS)-tier software runs on  the EIS server.

J2EE architecture supports component-based development of multi-tier enterprise applications. A J2EE application system typically includes the following tiers:

§ Client tier: In the client tier, Web components, such as Servlets and JavaServer Pages (JSPs), or standalone Java applications provide a dynamic interface to the middle tier.

§ Middle tier: In the server tier, or middle tier, enterprise beans and Web Services encapsulate reusable, distributable business logic for the application. These server-tier components are contained on a J2EE Application Server, which provides the platform for these components to perform actions and store data.

§ Enterprise data tier: In the data tier, the enterprise's data is stored and persisted, typically in a relational database.

Enterprise Application is designed into 6 logical  layers,  which  is  related  to  logic  of  client  tier,  middle tier and database tier. It defines which layer belongs to which tier.

§ Presentation Manager

The presentation manager defines the user interface. It always resides on the client  tier.  It  manages the information displayed to the user.

§ Presentation Logic

The presentation logic defines the navigation system of user interface, how and what will be displayed to the user. It may reside the client tier or business tier or database tier based on thin client and thick client and application tier.

§ Application Logic

Application logic defines the actual application logic it with. Application logic can be connectivity, validation etc. It may reside the client tier or business tier or database tier based on thin client and thick client and application tier.

 

§ Business Logic

The business logic layer contains the business rules of the application.  It  should  be shared with  the whole application. It may reside business tier or database tier based on thin client and thick client and application tier.

§ Database Logic


The database logic defines the table structure and the relationship between the tables. It also includes all the constraints of the table. It always reside with database tier.

§ Database Manager

The Database Manager stores the persistent data. It always resides with database tier.

Wednesday, 23 February 2022

Multi Language Website Using HTML

 Convert Your Website To Hindi, Gujarati, English, Arabic etc....


Example Here:


<script src="http://translate.google.com/translate_a/element.js?cb=loadGoogleTranslate"></script>

<script>

function loadGoogleTranslate()

{

new google.translate.TranslateElement("myid")

}

</script>

<div id="myid">Choose Language</div>


<h1>Welcome to my Website</h1>

<h1>Simple Way to Create MultiLingual Website</h1>

<h3>Google Translator Script Use to Convert All Over Language Simple Steps</h3>

<h2>Like Share and Subscribe Our Avadh Tutor Channel</h2>