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. 









Insert, Update and Delete data using Hibernate with MySQL Insert, Update and Delete data using Hibernate with MySQL Reviewed by Ravi Yasas on 11:13 PM Rating: 5

1 comment:

  1. Can you upload this project again?
    Best regardes

    ReplyDelete

Powered by Blogger.