Sunday, December 14, 2014

Insert, Update and Delete data using Hibernate with MySQL

After a long time I'm back. I think you have got an idea about Hibernate integration to your Simple Java application in my previous post. Here I'm going to explain how to use Hibernate to insert, update and delete data in GUI application with MySQL database. I have posted a post to do this using JDBC. Here I'm going to do this using Hibernate. Before you implement this, you need to create a database for this application. I have used, I previously  created database in previous post. You can download that sql script and create the database with data.


Create the GUI for application


  1. First of all lets create a package called Mobile.ui
  2. Then I created a JFrame Form called custom_gui.java




Then you need to create following type of GUI. It may easy to go through with this tutorial. You can also download the project file and easily import it to NetBeans.



It looks like this. It is better if you can refer variable names of these text boxes and buttons that I used. 







Main functions



It is very difficult to explain everything about this application. Because there are many functions. First of all you need to think the logic of this application. Then it will be easy to get an idea about HQL scripts. 


Search an item



In my GUI application you can see a button called search. You can search any data which has been stored in the database. You can search by brand or model. Or else you can search by using both of them. But I skipped searching by brand + model + price. I assume that a model cannot be duplicated with different prices. 

I used a set of if statements to check that availability when searching. Easily you can understand about this.


executeHQL() function


I have created this function to list down the extracted data from the database.



public void executeHQL(String hql){
        
        try{ 
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();

            Query query = session.createQuery(hql);
            List list = query.list();
            
            if(list.isEmpty()){
                JOptionPane.showMessageDialog(null, "No match found");
            }
            else{
                display(list);
            }
            
            session.getTransaction().commit();
            
        }catch(HibernateException e){
            e.printStackTrace();
        }
    }



display() function



This function is used to display data on the table. There are two vectors to create table headers and table data. This will display data row by row.


public void display(List list){
        
        Vector<String> tableHeaders = new Vector<String>();
        Vector tableData = new Vector();
        
        tableHeaders.add("id");
        tableHeaders.add("brand");
        tableHeaders.add("model");
        tableHeaders.add("price");
        
        for(Object obj : list){
            
            Mobiles mobiles = (Mobiles) obj;
            Vector<Object> row = new Vector<Object>();
            
            row.add(mobiles.getId());
            row.add(mobiles.getBrand());
            row.add(mobiles.getModel());
            row.add(mobiles.getPrice());
            tableData.add(row);
        }
        table.setModel(new DefaultTableModel(tableData, tableHeaders));
    }




add_item() function


I have created this function to add new item to the database. There is a method called save() to do this task. There I created a instance called mobile which belongs to Mobiles.java class. This class is used to get values and set them. Once you have done this task, you need to use commit() method. 

private void add_item(){
        try{
            
            if(brand.getText().isEmpty() == true || model.getText().isEmpty() == true || price.getText().isEmpty() == true){
                JOptionPane.showMessageDialog(null, "Please fill all fields to add item");
            }
            else{
                Session session = HibernateUtil.getSessionFactory().openSession();
                session.beginTransaction();

                Mobiles mobiles = new Mobiles();
                mobiles.setBrand(brand.getText());
                mobiles.setModel(model.getText());
                mobiles.setPrice(Integer.valueOf(price.getText()));

                session.save(mobiles);
                session.getTransaction().commit();
                session.close();
                JOptionPane.showMessageDialog(null, "Data added succesfully !");
            }
            
        }catch(HibernateException e){
            JOptionPane.showMessageDialog(null, "Error occured !");
            e.printStackTrace();
        }
    }




update_item() function


private void update_item(){
        try{
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();

            Mobiles mobiles = new Mobiles();
            mobiles.setId(Integer.valueOf(id.getText()));
            mobiles.setBrand(brand.getText());
            mobiles.setModel(model.getText());
            mobiles.setPrice(Integer.valueOf(price.getText()));

            session.update(mobiles);
            session.getTransaction().commit();
            session.close();
            JOptionPane.showMessageDialog(null, "Data updated succesfully !");
            
        }catch(Exception e){
            
            JOptionPane.showMessageDialog(null, "Error occured !");
            e.printStackTrace();
        }
    }



delete_item() function


private void delete_item(){
        try{
            Session session = HibernateUtil.getSessionFactory().openSession();
            session.beginTransaction();
            
            Mobiles mobiles = new Mobiles();
            mobiles.setId(Integer.valueOf(id.getText()));
            
            session.delete(mobiles);
            session.getTransaction().commit();
            session.close();
            JOptionPane.showMessageDialog(null, "Data deleted succesfully !");
            
        }catch(HibernateException e){
            JOptionPane.showMessageDialog(null, "Error occured !");
            e.printStackTrace();
        }
    }




select_table() function



This method is used to selections of the table. You can just select any data on the table and edit them.

public void select_table(){
        int row = table.getSelectedRow();
        
        id.setText(table.getModel().getValueAt(row, 0).toString());
        brand.setText(table.getModel().getValueAt(row, 1).toString());
        model.setText(table.getModel().getValueAt(row, 2).toString());
        price.setText(table.getModel().getValueAt(row, 3).toString());
    }




This is little bit long. But it is very easy to understand. I have used many pre defined method in this program. It is better if you can go with Oracle documentation to get the explanation of these methods.

You can download full code(project file) using following link. Just try and enjoy with Hibernate. See you soon with another post. 









Thursday, September 4, 2014

Your first Hibernate project with MySQL



This post is the first post which is about Hibernate. I want to give you a brief introduction about, how to use Hibernate and configure Hibernate files with MySQL. This will be the widest post in this blog. 


1. Create a database for the project



I'm going to create Database called shop and table within it called mobiles. I have already added some data into this table as follows. For testing purposes I have added more data into that table. You can download full sql script below.



create database shop;

use shop; 

create table mobiles(
 id int primary key auto_increment,
 brand varchar(50),
 model varchar(50),
 price int 
);

insert into mobiles (brand, model, price) values
('Nokia','Lumia 1020',700),
('Sony','Z2',600),
('HTC','OneMax',800),
('Apple','5S',900);



2. Create simple Java Application



No need to demonstrate this. Because this is very easy. You just need to create simple Java application and name it as "HibernateDemo" but don't create the main class(uncheck the tick).







3. Adding Hibernate and MySQL libraries



In this tutorial series I am using NetBeans 8.0 it comes with Hibernate 4 libraries. You know how to add library into your project. Just right click on the Libraries in your project. Then click on Add library. Then select Hibernate 4.x and add it. 



In this project we use MySQL. So we need to add MySQL JDBC Driver also. 


4. Create new connection



Now I'm going to create a new connection with the database that I have created. Just go to Services tab( If you can't find it, go to Window in the menu ). Then right click on it and do as follows.





Select the Driver


Type the database name(shop) and type the MySQL password.
If connection is succeeded go to Next


Nothing to change, click Next


Finish it




5. Add Hibernate Configuration file














Finally you did it. But you need to change some settings to easier future works.


  • Adding hibernate.show_sql property
Hibernate uses HQL( Hibernate Query Language ). This property is used to enable the logging of all the generated sql statements to the console. Mainly this is used for trouble shooting. 






Then you can add hibernate.format_sql property also.


  • Add hibernate.query.factory_class property
This is use to map hibernate queries to sql queries.











6. Add Hibernate Reverse Engineering file.













To learn more about Reverse Engineering Wizard, Click here.

7. Adding Hibernate mapping file and POJOs from database














Now your project has been configured to use Hibernate.  Lets see how to run simple HQL query.


8. Run HQL command




Right click on Hibernate.cfg.xml file
Select Run HQL Query






This is the way to configure your project that enables to use Hibernate. In next post you will learn how to use Hibernate to insert, update and delete data in your database. Here is the zipped project file in NetBeans.






Saturday, August 23, 2014

Implicit variables and objects in JSP



This is another important lesson in JSP. Before start this section it is better if you can look at our previous examples that have been done using JSP. In  this examples we used some variables without declaration and initialization (out,page...etc). JSP engine makes nine implicit variables to  the JSP page.

The objects that these variables are refer to are called implicit objects.


application variable and object


This variable is belongs to javax.servlet.ServletContext class. This refers to the environment of the web application. 

The application object is a representation of the JSP page through its entire life circle. IT is created when the JSP page is initialized and it will be removed by jspDestroy() method.

<% out.print(application.getServerInfo()); %>



session variable and object


You have learnt a attribute called session in JSP directives. This implicit variable is declared only if the session attribute  of the page directive is true. If session="false", JSP engine doesn't declare this variable. The session object is a instance of javax.servlet.http.HttpSession interface. This is used to track client sessions.

<%@page session="true" %>

<% out.print(session.getId());  %>



request / responce variable and object


These two implicit variables are related to javax.servlet.http.HttpServletRequest and javax.servlet.http.HttpServletResponce interfaces. The JSP engine creates new request objects for each and every client requests and also creates response objects to response clients. There are so many method associated with request and response objects.

<%
    String filePath = request.getServletPath();
    out.print("Your file path is: " + filePath);
%>


config variable and object


config variable is a type of javax.servlet.ServletConfig. This object allows to programmer to access to parameters of the JSP engine such as path, location, file name...etc.

<% out.print(config.getServletContext()); %>



out variable and object


This is a instance of javax.servlet.jsp.JspWriter class. This object has similar methods as PrintWriter class in Java. But additionally it has some methods to deal with buffering. This can be used directly in scriptlets and indirectly in expressions.  

<% out.print("Hi one"); %>

<%= "Hi two" %>



page variable and object


This is a instance of java.lang.Object class. This is entirely talk about the whole page and used to call the methods defined by the translated servlet class.

<% out.print(page.getClass().toString()); %>



pageContext variable and object



This object is also use to represent entire JSP page and it is a instance of javax.servlet.jsp.PageContext. pageContext class is an abstract class which stores references to the implicit objects. This class provide methods to set and get attributes.

<% pageContext.setAttribute("i", 10);  %>
<% out.print(pageContext.getAttribute("i"));   %>



exception variable and object


This is a instance of java.lang.Throwable interface. This can be used only if the page is set to a error page using isErrorPage = true. If it is set to true, then you can get the exception messages. 

<html><body>
<%@ page isErrorPage='true' %>
Error Message: <%=exception.toString()%> 
</body></html>






Thursday, August 14, 2014

JSP JavaBeans


What is JavaBean ?


JavaBean is a special Java class which is written according to the JavaBean API. There are conventions for JavaBeans.

  • The class should be serializable.
  • The class must have a public constructor (no arguments). 
  • It can have getter and setter methods for every property in the class.

JavaBean naming conventions


There is a post for Java naming rules in this blog. You can refer it for more details.

Example for JavaBean



package user;

import java.io.Serializable;

public class JavaBeanExample implements Serializable{
    
    private String name=null;
    //setProperty
    public void setName(String name){
        this.name=name;
    }
    
    //getProperty
    public String getName(){
        return name;
    } 
}


JavaBean with JSP



You can access JavaBeans through JSP. To do this task we use jsp:useBean action with few attributes. Here is an example that shows how to add useBean action into your JSP page.


<jsp:useBean id="Bean ID" scope="Bean's scope"/>


jsp:useBean attributes



There you have seen what are the attribute that can be used with jsp:useBean. There are few rules that you need to follow writing jsp pages.

  • id attribute is mandatory. This is the unique identifier of the bean.
  • scope attribute is optional. Default value is page. You cannot use session scope if session attribute of page directive is set to false.
  • Other three attributes can be used according to following combinations. At least one of them should be mentioned.
      1. class
      2. type
      3. class + type
      4. beanName + type

jsp:setProperty action



In JavaBean class there are setter and getter methods as I mentioned before. This setProperty action is used set methods. Here you can see how to use it in JSP.

<jsp:setProperty name="bean's id" property="property name" value="value">

jsp:setProperty attributes




As you can see there are only four attributes in jsp:setProperty. You need to understand few things before step forward into jsp:getProperty.


  • name attribute is mandatory. Because this is used to identify the bean. This value should be same as the id of the jsp:useBean action.
  • property attribute is also mandatory. It indicates the property of the bean to be set. You can set all the properties to respect values using " * " for property attribute. (property = "*")
  • value is optional attribute. Look at the following codes. Both are same.

<jsp:setProperty name="userName" property="firstName" value="Ann">

Above code is equal to following scriplet code.

<% userName.setFirstName("Ann") %>


  • Instead of using value attribute it can be used  param attribute to define requested parameters. Following codes are equivalent.

<jsp:setProperty name="userName" property="firstName" param="newName">


Above code is equal to following scriptlet code.

<% userName.setName(request.getParamter("newName")) %>


jsp:getProperty action



This is used to retrieve and print values of the bean. You can use it as follows.

<jsp:getProperty name="beanInstanceName" property="propertyName">



jsp:getProperty attributes



Following JSP code and Scriptlet  codes are equal.

<jsp:getProperty name="userName" property="firstName">

This is equal to, 

<% out.print(userName.getFirstName()); %>


Now it is the time to see what really happens in coding. Here is an example that demonstrate how to use JavaBeans with JSP.


EmployeeBean.java


package factory;

import java.io.Serializable;

public class EmployeeBean implements Serializable{
    
    private String name = null;
    private String id = null;

    public String getName(){
        return name;
    }
    
    public String getId(){
        return id;
    }
    
    public void setName(String name){
        this.name = name;
    }
    
    public void setId(String id){
        this.id = id;
    }
}


home.jsp


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <body>
        <h2>Employee details</h2>
        
        <form method="post" action="employeeJsp.jsp">
            <label>Name :</label> <input type="text" name="name"></br>
            <label>ID :</label> <input type="text" name="id"></br>
            <input type="submit" value="Submit">
        </form>
    </body>
</html>





employeeJsp.jsp



<%@page contentType="text/html" pageEncoding="UTF-8"%>
<jsp:useBean id="factory" class="factory.EmployeeBean" scope="session"/>
<jsp:setProperty name="factory" property="name"/>
<jsp:setProperty name="factory" property="id"/>
<%-- 
Instead of using above two statemens, you can use following code
    <jsp:setProperty name="factory" property="*"/>
--%>

<!DOCTYPE html>
<html>
    <body>
        <h1>Hi <jsp:getProperty name="factory" property="name"/> ! </h1>
        <h2>Your ID is <jsp:getProperty name="factory" property="id"/> </h2>
        <%--
        Instead of using jsp:getProperty, you can use following code
            <%= factory.getName() %>
            <%= factory.getId() %>
        --%>
    </body>
</html>


Download project file










Tuesday, August 12, 2014

Re-usability of JSP



JSP always make your code easier to handle. If you are familiar with php you can remember there is something that you can include a php page to a another page. Think about a simple html page.




You can divide your php file into few sections like above image. Then you can create separate web pages like header.php, nav.php and footer.php likewise. Then once you need that section, you can include it using php include command. 

In JSP there is a mechanism to do that task. JSP can reuse web components. This can be done in two ways.

  1. Static
  2. Dynamic

    Static include



    This is very similar to php include. But in this method you can include any text based file (JSP, HTML, XML or even text file) into your JSP page. The content of another file is included with the current JSP file. In translation it looks like a single servlet. This can be done in two ways as follows. 


    <%@include file="mango.jsp" %>
        
    <jsp:directive.include file="Cherry.jsp"/>
    
    

    Here is an example to understand about Static include. I have created four files to demonstrate this. You can download NetBeans project file below and try it. Final browser view should be like this.


    Download source code



    Rules of Static include

    • file name attribute cannot be an expression.
    • file attribute cannot pass any parameters.

    Dynamic include



    In this way, If you request a JSP page, it sends a request to the object and the output is included in current JSP file. This can be done in two ways using include and forward.


    <jsp:include page="url" flush="true" />
    <jsp:forward page="url" />
    
    

    Using include

    This can be done as follows. You can include files using following methods.


       <%
           RequestDispatcher dispatcher = request.getRequestDispatcher("newPage.jsp");
           dispatcher.include(request, response);
       %>
    
    

    Method 2
       
       <%
           pageContext.include("newPage.jsp");
       %>
    
    

    Method 3

        <jsp:forward page="newPage.jsp" flush="true"/>
    
    


    Using forward

    There are three ways to perform this task.

    Method 1

       <%
           RequestDispatcher dispatcher = request.getRequestDispatcher("newPage.jsp");
           dispatcher.forward(request, response);
       %>
    
    

    Method 2
       
       <%
           pageContext.forward("newPage.jsp");
       %>
    
    

    Method 3

        <jsp:forward page="newPage.jsp"/>
    
    


    Here is an example for both Including and forwarding. You can import it and run on NetBeans. Then try to understand what is the different between Static and Dynamic inclusions using the result.