This is default featured slide 1 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 2 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 3 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 4 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

This is default featured slide 5 title

Go to Blogger edit html and find these sentences.Now replace these sentences with your own descriptions.

Friday, July 20, 2012

JDBC Vs Hibernate

7.1 Why is Hibernate better than JDBC

1)   Relational Persistence for JAVA

Working with both Object-Oriented software and Relational Database is complicated task with JDBC because there is mismatch between how data is represented in objects versus relational database. So with JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.

2)   Transparent Persistence

The automatic mapping of Java objects with database tables and vice versa is called Transparent Persistence. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. With JDBC this conversion is to be taken care of by the developer manually with lines of code.

3)   Support for Query Language

JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.

4)   Database Dependent Code

Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.

5)   Maintenance Cost

With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.

6)   Optimize Performance

Caching is retention of data, usually in application to reduce disk access. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many


times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. With JDBC, caching is maintained by hand-coding.

7)   Automatic Versioning and Time Stamping

By database versioning one can be assured that the changes done by one person is not being roll backed by another one unintentionally. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow to save it because this user does not has updated data. In JDBC there is no check that always every user has updated data. This check has to be added by the developer.

8)   Open-Source, Zero-Cost Product License

Hibernate is an open source and free to use for both development and production deployments.

9)   Enterprise-Class Reliability and Scalability

Hibernate scales well in any environment, no matter if use it in-house Intranet that serves hundreds of users or for mission-critical applications that serve hundreds of thousands. JDBC can not be scaled easily.

Java Prepared Statements



Java JDBC Prepared statements are pre-compiled SQL statements. Precompiled SQL is useful if the same SQL is to be executed repeatedly, for example, in a loop. Prepared statements in java only save you time if you expect to execute the same SQL over again. Every java sql prepared statement is compiled at some point. To use a java preparedstatements, you must first create a object by calling the Connection.prepareStatement() method. JDBC PreparedStatements are useful especially in situations where you can use a for loop or while loop to set a parameter to a succession of values. If you want to execute a Statement object many times, it normally reduces execution time to use a PreparedStatement object instead.

The syntax is straightforward: just insert question marks for any parameters that you'll be substituting before you send the SQL to the database. As with CallableStatements, you need to call close() to make sure database resources are freed as soon as possible. Below is a JDBC Program showing the use of jdbc prepared statements to insert data into tables using jdbc programming.
You need to supply values to be used in place of the question mark placeholders (if there are any) before you can execute a PreparedStatement object. You do this by calling one of the setXXX methods defined in the PreparedStatement class. There is a setXXX method for each primitive type declared in the Java programming language.

PreparedStatement pstmt = con.prepareStatement("update Orders set pname = ? where Prod_Id = ?");
pstmt.setInt(2, 100);
pstmt.setString(1, "Bob");
pstmt.executeUpdate();

An important feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. This SQL statement is sent to the DBMS right away, where it is compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement SQL statement without having to compile it first.
Using Prepared Statements in jdbc, objects can be used for SQL statements with no parameters, you probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it.

 source: http://www.jdbc-tutorial.com/

How many Types of Statements in JDBC ?

In JDBC there are three types of Statements:

1).Statement
2).PreparedStatement
3).CallableStatement

Once a connection is obtained we can interact with the database.These three are Interfaces.By using these three statements we can do the operations on Databases using the methods provided in Interfaces.

Statement: Use for general-purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters.

PreparedStatement   : Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime.

CallableStatement   : Use when you want to access database stored procedures. The CallableStatement interface can also accept runtime input parameters.

JDBC - Simple Statement

The Statement interface lets you execute a simple SQL statement with no parameters. The SQL instructions are inserted into the Statement object when the Statement.executeXXX method is called.

Query Statement: This code segment creates a Statement object and calls the Statement.executeQuery method to select text from the dba database. The results of the query are returned in a ResultSet object. How to retrieve results from a ResultSet object is explained in Result Sets below.



Statement stmt = con.createStatement();
 ResultSet results = stmt.executeQuery("SELECT TEXT FROM dba ");


Update Statement: This code segment creates a Statement object and calls the Statement.executeUpdate method to add an email address to a table in the dba database.

  String updateString =  "INSERT INTO dba VALUES (some text)";
  int count = stmt.executeUpdate(updateString);

JDBC - CallableStatement

The CallableStatement interface allows the use of SQL statements to call stored procedures. Stored procedures are programs that have a database interface. These programs possess the following:
1)    They can have input and output parameters, or parameters that    are   both input and output.
2)    They can have a return value.
3)    They have the ability to return multiple ResultSets.

        Conceptually in JDBC, a stored procedure call is a single call to the database, but the program associated with the stored procedure may process hundreds of database requests. The stored procedure program may also perform a number of other programmatic tasks not typically done with SQL statements.

        Creating CallableStatements

        The prepareCall method is used to create new CallableStatement objects. As with the prepareStatement method, the SQL statement must be supplied at the time that the CallableStatement object is created. At that time, the SQL statement is precompiled. For example, assuming a Connection object named conn already exists, the following creates a CallableStatement object and completes the preparation phase of getting the SQL statement ready for processing within the database:

            
        PreparedStatement ps = conn.prepareStatement("? = CALL ADDEMPLOYEE(?, ?, ?");


        Handling parameters

        As stated, CallableStatement objects may take three types of parameters:

            IN

            IN parameters are handled in the same manner as PreparedStatements. The various set methods of the inherited PreparedStatement class are used to set the parameters.

            OUT

            OUT parameters are handled with the registerOutParameter method. The most common form of registerOutParameter takes an index parameter as the first parameter and an SQL type as the second parameter. This tells the JDBC driver what to expect for data from the parameter when the statement is processed. There are two other variations on the registerOutParameter method that can be found in the java.sql package Javadoc.

            INOUT

            INOUT parameters require that the work for both IN parameters and OUT parameters be done. For each INOUT parameter, you must call a set method and the registerOutParameter method before the statement can be processed. Failing to set or register any parameter results in an SQLException being thrown when the statement is processed.

        Using CallableStatement methods to call stored procedures

        To call stored procedures, you invoke methods in the CallableStatement class. The basic steps are:

        --->Invoke the Connection.prepareCall method to create a CallableStatementobject.
        --->Invoke the CallableStatement.setXXX methods to pass values to the input (IN) parameters.
        --->Invoke the CallableStatement.registerOutParameter method to indicate which parameters are output-only (OUT) parameters, or input and output (INOUT) parameters.
        --->Invoke one of the following methods to call the stored procedure: 
        --->CallableStatement.executeUpdate
        --->Invoke this method if the stored procedure does not return result sets.
        --->

        1. --->CallableStatement.executeQuery
          Invoke this method if the stored procedure returns one result set.
          CallableStatement.execute
          Invoke this method if the stored procedure returns multiple result sets.



        2. --->If the stored procedure returns result sets, retrieve the result sets. SeeRetrieve multiple result sets from a stored procedure in a JDBC application.



        3. --->Invoke the CallableStatement.getXXX methods to retrieve values from the OUT parameters or INOUT parameters.



        4. --->Invoke the CallableStatement.close method to close theCallableStatement object when you have finished using that object.


        The following code illustrates calling a stored procedure that has one input parameter, four output parameters, and no returned ResultSets. The numbers to the right of selected statements correspond to the previously-described steps. 

        Types of JDBC Drivers in JAVA

        JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:
        Type 1: JDBC-ODBC Bridge driver (Bridge)
        Type 2: Native-API/partly Java driver (Native)
        Type 3: AllJava/Net-protocol driver (Middleware)
        Type 4: All Java/Native-protocol driver (Pure)

        4 types of jdbc drivers are elaborated in detail as shown below:

        Type 1 JDBC Driver

        JDBC-ODBC Bridge driver
        The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. ODBC is a generic API. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available.
        Type 1: JDBC-ODBC Bridge
        Advantage
        The JDBC-ODBC Bridge allows access to almost any database, since the database’s ODBC drivers are already available.
        Disadvantages
        1. Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable.
        2. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
        3. The client system requires the ODBC Installation to use the driver.
        4. Not good for the Web.

        Type 2 JDBC Driver

        Native-API/partly Java driver
        The distinctive characteristic of type 2 jdbc drivers are that Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database. Some distinctive characteristic of type 2 jdbc drivers are shown below. Example: Oracle will have oracle native api.
        Type 2: Native api/ Partly Java Driver
        Advantage
        The distinctive characteristic of type 2 jdbc drivers are that they are typically offer better performance than the JDBC-ODBC Bridge as the layers of communication (tiers) are less than that of Type
        1 and also it uses Native api which is Database specific.
        Disadvantage
        1. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
        2. Like Type 1 drivers, it’s not written in Java Language which forms a portability issue.
        3. If we change the Database we have to change the native api as it is specific to a database
        4. Mostly obsolete now
        5. Usually not thread safe.

        Type 3 JDBC Driver

        All Java/Net-protocol driver
        Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middle-tier server can in turn use Type1, Type 2 or Type 4 drivers.
        Type 3: All Java/ Net-Protocol Driver
        Advantage
        1. This driver is server-based, so there is no need for any vendor database library to be present on client machines.
        2. This driver is fully written in Java and hence Portable. It is suitable for the web.
        3. There are many opportunities to optimize portability, performance, and scalability.
        4. The net protocol can be designed to make the client JDBC driver very small and fast to load.
        5. The type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced
        system administration such as logging and auditing.
        6. This driver is very flexible allows access to multiple databases using one driver.
        7. They are the most efficient amongst all driver types.
        Disadvantage 
        It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.

        Type 4 JDBC Driver

        Native-protocol/all-Java driver
        The Type 4 uses java networking libraries to communicate directly with the database server.
        Type 4: Native-protocol/all-Java driver
        Advantage
        1. The major benefit of using a type 4 jdbc drivers are that they are completely written in Java to achieve platform independence and eliminate deployment administration issues. It is most suitable for the web.
        2. Number of translation layers is very less i.e. type 4 JDBC drivers don’t have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good.
        3. You don’t need to install special software on the client or server. Further, these drivers can be downloaded dynamically.
        Disadvantage
        With type 4 drivers, the user needs a different driver for each database.

        Thursday, July 19, 2012

        Java Students - Odisha Students - Orissa Students


        This is the portal created by Java Students learned JAVA from various institutions like SATHYA TECHNOLOGIES, NARESH I TECHNOLOGIES, etc

        Here you will get tutorials, interview questions and downloads about the followings :

        CORE JAVA
        JDBC
        SERVLET
        JSP
        HIBERNATE
        STRUTS
        SPRING
        J2EE
        EJB
        SERVER
        And many more