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.

Saturday, July 28, 2012

JSP Tag Libraries in Breif



You have many options when it comes to generating dynamic content inside the JSP page.

These options are as follows :
  • Scripting elements calling servlet code directly
  • Scripting elements calling servlet code indirectly (by means of utility     classes)
  • Beans
  • Servlet/JSP combo (MVC)
  • MVC with JSP expression language
  • Custom tags

The options at the top of the list are much simpler to use and are just as legitimate as the options at the bottom of the list. However, industry has adopted a best practice to avoid placing Java code inside the JSP page. This best practice stems from it being much harder to debug and maintain Java code inside the JSP page. In addition, JSP pages should concentrate only on the presentation logic. Introducing Java code into the JSP page tends to divert its purpose and, inevitably, business logic starts to creep in. To enforce this best practice, version 2.4 of the servlet specification went so far as to provide a way to disable any type of JSP scripting for a group of JSP pages. We discuss how to disable scripting in Section 2.14 (Configuring JSP Pages).

That said, there are cases where the presentation logic itself is quite complex and using the non-Java code options in the JSP page to express that logic becomes either too clunky and unreadable or, sometimes, just impossible to achieve. This is where logic through the familiar HTML-like structures.

Although the SimpleTag API completely replaces the classic tag API, you should keep in mind that it works only in containers compliant with servlet specification 2.4 and above. Because there are still a lot of applications running on servlet 2.3-compliant containers, you should consider avoiding the SimpleTag API if you are not sure what type of container your code will end up on.

Tag Library Components :

To use custom JSP tags, you need to define three separate components :

- The tag handler class that defines the tag's behavior
- The TLD file that maps the XML element names to the tag implementations
- The JSP file that uses the tag library

Most people find that the first tag they write is the hardest—the difficulty being in knowing where each component should go, not in writing the components. So, we suggest that you start by just downloading the simplest of the examples of this chapter from http://volume2.coreservlets.com/ and getting those examples to work on your machine. After that, you can move on and try creating some of your own tags.

The Tag Handler Class :

When defining a new tag, your first task is to define a Java class that tells the system what to do when it sees the tag. This class must implement the SimpleTag interface. In practice, you extend SimpleTagSupport, which implements the SimpleTag interface and supplies standard implementations for some of its methods. Both the SimpleTag interface and the SimpleTagSupport class reside in the javax.servlet.jsp.tagext package.

The very first action the container takes after loading the tag handler class is instantiating it with its no-arg constructor. This means that every tag handler must have a no-arg constructor or its instantiation will fail. Remember that the Java compiler provides one for you automatically unless you define a constructor with arguments. In that case, be sure to define a no-arg constructor yourself.

The code that does the actual work of the tag goes inside the doTag method. Usually, this code outputs content to the JSP page by invoking the print method of the JspWriter class. To obtain an instance of the JstWriter class you call getJspContext().getOut() inside the doTag method. The doTag method is called at request time. It's important to note that, unlike the classic tag model, the SimpleTag model never reuses tag handler instances. In fact, a new instance of the tag handler class is created for every tag occurrence on the page. This alleviates worries about race conditions and cached values even if you use instance variables in the tag handler class.

You place the compiled tag handler in the same location you would place a regular servlet, inside the WEB-INF/classes directory, keeping the package structure intact. For example, if your tag handler class belongs to the mytags package and its class name is MyTag, you would place the MyTag.class file inside the WEB-INF/classes/mytags/ directory.

Example Tag Handler Class :

Code:
package javabynataraj;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

public class ExampleTag extends SimpleTagSupport {
  public void doTag() throws JspException, IOException {
    JspWriter out = getJspContext().getOut();
    out.print("<b>Hello World!</b>");
  }
}

The Tag Library Descriptor File :

Once you have defined a tag handler, your next task is to identify this class to the server and to associate it with a particular XML tag name. This task is accomplished by means of a TLD file in XML format. This file contains some fixed information (e.g., XML Schema instance declaration), an arbitrary short name for your library, a short description, and a series of tag descriptions.

Example Tag Library Descriptor File :

Code:
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
  http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
  version="2.0">
  <tlib-version>1.0</tlib-version>
  <short-name>csajsp-taglib</short-name>
  <tag>
    <description>Example tag</description>
    <name>example</name>
    <tag-class>package.TagHandlerClass</tag-class>
    <body-content>empty</body-content>
    </tag>
</taglib>

We describe the details of the contents of the TLD file in later sections. For now, just note that the tag element through the following subelements in their required order defines the custom tag.

description : This optional element allows the tag developer to document the purpose of the custom tag.

name : This required element defines the name of the tag as it will be referred to by the JSP page (really tag suffix, as will be seen shortly).

tag-class : This required element identifies the fully qualified name of the implementing tag handler class.

body-content : This required element tells the container how to treat the content between the beginning and ending occurrence of the tag, if any. The value that appears here can be either empty, scriptless, tagdependent, or JSP.

The value of empty means that no content is allowed to appear in the body of the tag.

This would mean that the declared tag can only appear in the form :

Code:
<prefix:tag/>
      or
<prefix:tag></prefix:tag>


(without any spaces between the opening and closing tags). Placing any content inside the tag body would generate a page translation error.

The value of scriptless means that the tag body is allowed to have JSP content as long as it doesn't contain any scripting elements like <% ... %> or <%= ... %>. If present, the body of the tag would be processed just like any other JSP content.

The value of tagdependent means that the tag is allowed to have any type of content as its body. However, this content is not processed at all and completely ignored. It is up to the developer of the tag handler to get access to that content and do something with it. For example, if you wanted to develop a tag that would allow the JSP page developer to execute an SQL statement, providing the SQL in the body of the tag, you would use tagdependent as the value of the body-content element.

Finally, the value of JSP is provided for backward compatibility with the classic custom tag model. It is not a legal value when used with the SimpleTag API.

Note that there is no legal way of allowing any scripting elements to appear as the tag body under the new SimpleTag API model.

Core Warning :

When using the SimpleTag API, it is illegal to include scripting elements in the body of the tag.

The TLD file must be placed inside the WEB-INF directory or any subdirectory thereof.

Example JSP File :

Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>Example JSP page</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<%@ taglib uri="/WEB-INF/tlds/example.tld"
             prefix="test" %>
<test:example/>
<test:example></test:example>
</BODY></HTML>

Static ContextPath to Dynamic ContextPaths in Jsp and JS pages



Changing Static ContextPath to Dynamic ContextPath references in JSP and JS pages in our project. If you are working with any project on java and jsp technologies, if the requirement may come to change the static context paths to dynamic context path.

What is the need to change context path from static to dynamic context path?

While developing our application we use to develop to put our contextPath directly in some areas like for links and mostly for images we give absolute paths with context. We put this in developing the project. After developing the project , it goes to Testing after then to production.
Let us assume our project contextPath is "/myproj"


Now this project is going for testing, then the testers change the contextPath as theirs purpose like "/myprojTest" then the images and links all will broken. For this purpose the dynamic context references will be use full.

1. Change to Dynamic ContextPaths in Pager Tags of JSP pages.

The Old Code having Static ContextPath:

<pg:pager maxPageItems="10"

            prevNextUrl="/myproj/auto/sheetAuditResults.do"

            url="/myproj/auto/sheetAuditResults.do" 

            name="caseResponseForm">
               -------
              ------------
</pg:pager>

Here the ContextPath is /myproj need to change to Dynamic path as given below:

use jsp:useBean tags to define the variable name and get the contextPath then assign the link to the variables pnUrlName and urlName in the scriptlets.

<jsp:useBean id="pnUrlName" class="java.lang.String" scope="page" />

<jsp:useBean id="urlName" class="java.lang.String" scope="page" />

      <%pnUrlName = request.getContextPath()+"/auto/sheetAuditResults.do"; %>

      <%urlName = request.getContextPath()+"/auto/sheetAuditResults.do"; %>

      <pg:pager maxPageItems="10"

            prevNextUrl="<%=pnUrlName %>"

            url="<%=urlName %>" 

            name="auditInformationResultsResponseForm">


2. Change ContextPath for images in Jsp page

<img src="/myproj/images/calbtn.gif" border="0" alt="popup selection calendar ">
We have to change the static contextPath /myproj to dynamically.

for that we have to declare in jsp page below to the taglib tags. as given below:
<%@ taglib uri="/WEB-INF/tlds/struts-core.tld" prefix="c" %>
<c:set var="path" value="${pageContext.request.contextPath}"/>

Convert the image with static contextPath to dynamically as given below

<img src="<c:out value="${path}"/>/images/calbtn.gif" border="0" alt="popup selection calendar">

3. Change ContextPath in javascript file to open a new window.

caseWindow = window.open('/myapp/cases/displayCase.do?previousPage=addDeposit'+jsessionId,'
DN_modalEms','width=800,height=600,resizable=yes,
scrollbars=yes,status=yes,menubar=no,toolbar=no,modal=yes');

Then change the contextPath /myproj to dynamic contextPath

As we did before for the jsp page we have to define the contextPath to a variable path using jsp core tag library tags.
<c:set var="path" value="${pageContext.request.contextPath}"/>
use the contextPath in the javascript function:
<script type="text/javascript">
      contextPath = '<c:out value="${path}"/>';
</script>
modalCaseWindow = window.open(contextPath+'/cases/displayCreateCase1.do?previousPage=addDeposit'+jsessionId,'DN_modalEms',
'width=800,height=600,resizable=yes,scrollbars=yes,
status=yes,menubar=no,toolbar=no,modal=yes');

4.Change contextPath for hyperlinks:

<a href="/myproj/updateMyDeviceId.do?device=' + ent.deviceId + '">';
Change the static context root reference to dynamic contextPath for the hyperlink in jsp file as given below.

Use the same defined contextPath variable to use here. Actually the contextPath is global accessible in an application any where. NO need to define in every page of jsp.
<a href="'+ contextPath +'/updateMyDeviceId.do?device=' + ent.deviceId + '">';

5.Change contextPath in javascript file for image.

if (data.status == 1) {

                  $('#status').text('Enabled');
                  $('#circle').attr('src', '/myproj/images/green-circle.png')
                  $('#statusButton').val('Disable');
            }
Change the context path in the if condition. For this define a variable as ctx to get contextPath using request.getContextPath() method.

<script>var ctx = "<%=request.getContextPath()%>"</script>
Declare the ctx variable below to the taglib uri tags then we can use any where in the program.

if (data.status == 1) {
                  $('#status').text('Enabled');
                  $('#circle').attr('src',ctx+'/images/green-circle.png')
                  $('#statusButton').val('Disable');
            }


You might also like:     

Friday, July 20, 2012

Web application introduction.

WebApplication is a collection of web resources like HTML files, JavaScriptfiles, image files Servletsjsps and etc.

In order to make resources of a application as globally accessible resources developed as web resources of web-application each web-resource develops one webpage and this webpage is globally accessible page.
The web-application that is moved to internet network after development is called Website.

A web application contains two types of web-resources. 

**    Server side Web-resource    
**    Client side Web-resource
    A web resource that comes to browser(client) from web application placed in web-server/application server for execution is called client side web resource.

    EX:  HTML,JavaScript programs.

    The web-resource program that executed in the server(web-server/application server)is called server-side web-resource program.

    EX : Servlet,JSP
    • Don't decide weather web-server program is server-side or client side based on the place where it resides and decide based on the place where it executes.

    What is the difference between doGet() and doPost() methods ?

    The difference has given below......


     
    doGet

    doPost
    In doGet Method the parameters are appended to the URL and sent along with header information
    In doPost parameters are sent in separate line in the body
    Maximum size of data that can be sent using doget is 240 bytes
    There is no maximum size for data
    Parameters are not encrypted
    Parameters are encrypted
    DoGet method generally is used to query or to get some information from the server
    DoPost is slower compared to doGet since doPost does not write the content length
    DoGet should be idempotent. i.e. doget should be able to be repeated safely many times
    This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable for example updating stored data or buying items online.
    DoGet should be safe without any side effects for which user is held responsible.
    This method does not need to be either safe.

    Upload CSV file into MySql Database based on columns using Servlets and Java



    The CSV file is having multiple values to insert in perticular columns and rows in mysql database.

    Here we have two files so we have to insert in two tables .

    *** one is Header part file

    *** another is Detail part file

    Basically these two are to upload the questions and answers into the examination portal to upload question papers and answer paper in (Merit Tracking System project).

    First we have to do the things are Uploaded file has to save in perticular folder and then they have to insert the values into the database table.This is our main task to do.


    The required files to this program are 

    #1. index.jsp
    #2. succ.jsp
    #3. web.xml
    #4. DBConnection.java
    #5. SaveFile.java
    #6. UploadFile2DB.java

    and Some other libraries to add 


    #1. mysql-connector-java-3.1.11.jar
    #2. servlet-api.jar

    These are enough to our requirement add this files to your "lib" folder.



    #1. index.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
     pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    
    <form name="fileuploadform"
     action="http://localhost:8080/UploadCSV/uploadfile">Upload CSV
    File<br>
    Select the header file to upload <input type="file" name="filehdr" /><br>
    Select the detail file to upload <input type="file" name="filedtl" /><br>
    
    Please select a folder to which the file has to be uploaded. <input
     type="file" name="filefolder" /><br>
    <input type="submit" name="submit" value="submit"> </form>
    </html>

    #2. succ.jsp 

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    <b>The Files has been Uploaded into particular tables.</b>
    </body>
    </html>

    #3. DBConnection.java


    package com;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    
    public class DBConnection {
    static Connection con;
        
        public static Connection getConnection(){
            con=null;
            try{
                System.out.println("----------I am in DBConnection----------");
                Class.forName("com.mysql.jdbc.Driver");
                con=DriverManager.getConnection("jdbc:mysql://192.168.1.101:3306/test?user=test&password=test" );
                System.out.println("---------end of DBConnection----------");
            }catch(Exception e){
                e.getMessage();
            }
            return con;
        }
    }
    


    #4. SaveFile.java


    package com;
    
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class SaveFile extends HttpServlet {
        public void init(ServletConfig config)throws ServletException{
            super.init(config);
            System.out.println("The SaveFile iniated.^^^^^^^^^^^^^^^^^^^################");
        }
        
        public void service(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
            try{
                String pathheader=request.getParameter("filehdr");
                System.out.println("The pathheader is : "+pathheader);
                String pathdetail=request.getParameter("filedtl");
                System.out.println("The pathdetail is : "+pathdetail);
                
                String folderpath=request.getParameter("filefolder");    
                
                String filenamehdr=folderpath+pathheader.substring(pathheader.lastIndexOf('\\'));
                System.out.println("The file output path is : "+filenamehdr);            
                String filenamedtl=folderpath+pathdetail.substring(pathdetail.lastIndexOf('\\'));
                System.out.println("The file output path is : "+filenamedtl);
                
                FileInputStream fis=new FileInputStream(pathheader);
                FileOutputStream fos=new FileOutputStream(filenamehdr);
                
                byte buf[]=new byte[11024];
                fis.read(buf);
                fos.write(buf,0,buf.length);
                
                fis=new FileInputStream(pathdetail);
                fos=new FileOutputStream(filenamedtl);
                fis.read(buf);
                fos.write(buf,0,buf.length);
                
                if(fis!=null)
                    fis.close();
                if(fos!=null)
                    fos.close();
                
                System.out.println("------------------ Files are Saved in Folder-------------------");
                request.getRequestDispatcher("/uploaddata").forward(request, response);
    
            }catch(FileNotFoundException e){
                System.out.println(e.getMessage());
            }catch(IOException e){
                System.out.println(e.getMessage());
            }
        }
    
    
    }
    
    


    #5. UploadFile2DB.java


    package com;
    
    import java.io.BufferedReader;
    import java.io.FileReader;
    import java.io.IOException;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.util.StringTokenizer;
    
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class UploadFile2DB extends HttpServlet {
        public void init(ServletConfig config) throws ServletException{
            super.init(config);
            System.out.println("The UploadDataServlet2 iniated.");
        }
    
    
    
        public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {
            
            
            String filepathhdr=request.getParameter("filehdr");
            String filepathdtl=request.getParameter("filedtl");
            Connection con=DBConnection.getConnection();
            System.out.println("connection=----------->"+con);
            PreparedStatement pstmthdr=null;
            PreparedStatement pstmtdtl=null;
    
            int rowshdr=0;
            BufferedReader brhdr=new BufferedReader(new FileReader(filepathhdr));
            BufferedReader brdtl=new BufferedReader(new FileReader(filepathdtl));
            System.out.println("reading the file");
            String strLineHdr="";
            String strLineDtl="";
            String hdrstr="";
            String dtlstr="";
            StringTokenizer sthdr=null;
            StringTokenizer stdtl=null;
            //        String firstColumnData[]=new String[10];
            int lineNumberHdr=0;
            int lineNumberDtl=0;
            //        int line=1;
            try{
                pstmthdr=con.prepareStatement("insert into omts_onlinehdr values (?,?,?,?,?,?,?)");
                System.out.println("statement executed");
    
                while((strLineHdr=brhdr.readLine())!=null){
                    System.out.println("HEADERLINE"+strLineHdr);
                    int i=1;
                    if(!(lineNumberHdr==0)){
                        sthdr=new StringTokenizer(strLineHdr,",");
                        while(sthdr.hasMoreTokens()){
                            hdrstr=sthdr.nextToken();
                            System.out.println("HeaderString: "+hdrstr);
                            pstmthdr.setString(i++,hdrstr);
                            System.out.println("below insertion");
                        }
                        rowshdr=pstmthdr.executeUpdate();
                        System.out.println(rowshdr+" rows updated.");
                    }
                    lineNumberHdr++;
                }
                System.out.println("not in detail");
                pstmtdtl=con.prepareStatement("insert into omts_onlinedtl values (?,?,?,?,?,?,?)");
                System.out.println("ps executed");
    
                while((strLineDtl=brdtl.readLine())!=null){
                    System.out.println("detailLINE"+strLineDtl);
                    int i=1;
                    if(!(lineNumberDtl==0)){
                        stdtl=new StringTokenizer(strLineDtl,",");
                        while(stdtl.hasMoreTokens()){
                            dtlstr=stdtl.nextToken();
                            System.out.println("detail: "+dtlstr);
                            pstmtdtl.setString(i++,dtlstr);
                            System.out.println("below insertion");
                        }
                        int rowsdtl=pstmtdtl.executeUpdate();
                        System.out.println(rowsdtl+" rows are updated.");
                    }
                    lineNumberDtl++;
                }
                //con.commit();
            }
            catch(Exception e){
                System.out.println(e.getMessage());
            }
            finally
            {
                try {
                    con.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            response.sendRedirect("http://localhost:8080/UploadCSV/succ.jsp");
        }
    }
    


    Run your application using Tomcat webserver and it will displays index.jsp as welcome-file-list.



    By selecting CSV file  using browse button  of header part and detail part and set the path of the folder where you want to save the uploaded files and click on submit button.

    After completion of accessing two files into folders and databases it will displays as succ.jsp file as "successfully uploaded the two files".


    The Console will displays as the all the information what is going inside.
    Note: Use the MySql database or Oracle and give the driver name and url of the driver to connect Database in the DBConncetion class.


    DOWNLOAD SOURCE

    For Reference on Files:

    Difference between ServletContext and ServletConfig ?

    What is the Difference between ServletConfig and ServletContext.?


    ServletConfig:

    public interface ServletConfig

    ServletConfig encapsulates servlet configuration and gives access to the application (servlet context) object. Servlet initialization parameters appear in the servlet configuration file. Each servlet class may have several different servlet instances, one for each servlet parameters:


    1. One ServletConfig per servlet
    2. It is used to pass deploy-time info to servlet and configured in the deployment descriptor file. 
    3. it is used to access ServletContext 
    4. It is within the Servlet element in Deployment descriptor.
    5. It is accessed by using getServletConfig().getInitParameter("myname"); 
    6. It is available only to the servlet in which init-param is configured.

    Example: 


    ServletContext:

    public interface ServletContext

    ServletContexts encapsulate applications. Applications are generalized virtual hosts; a URL prefix defines a distinct application. So /myapp and /yourapp could define different applications. As a degenerate case, each virtual host has its own ServletContext. 

    1. It returns the current context of a web application running in a particular JVM.. 
    2. If the web application is distributed,it is one per JVM. 
    3. It is used to access the elements configured in deployment descriptor.
    4. It is accessed by using getServletContext().getInitParameter("myname"); 
    5. It is available to any servlet or jsp that is part of web application.


    Example:

    Introduction to JDBC

    JDBC stands for Java Database Connectivity allows developers to connect, query and update a database using the Structured Query Language. JDBC API standard provides Java developers to interact with different RDBMS and access table data through Java application without learning RDBMS details and using Database Specific JDBC Drivers.

    2.  JDBC Architecture

    JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database:

    open connection to database,

    use JDBC driver to send SQL queries to database,

    process the results that are returned, and

    close the connection.

    JDBC uses two architectures to communicate with database:

    1) The driver connects to database and executes SQL statements. Results are sent back from driver to driver manager and finally to the application.
    2) The JDBC driver communicates with ODBC driver. ODBC driver executes SQL query and then results are sent back to JDBC driver to driver manager and then to application.



    1. Introduction to JDBC
    2. JDBC Architecture 
    3. Interaction of JDBC with Database 
    4. Introduction to Hibernate 
    5. Hibernate Architecture 
    6. Hibernate Communication with RDBMS 
    7. Hibernate vs. JDBC 
    7.1. Advantage of Hibernate over JDBC 
    7.2. Disadvantages of Hibernate 



    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/