Fetch Data on to a specific field and insert data into the database using hibernate by R4R Team

In hibernate when we want to fetch data on a specific field of the form then we need to perform some basic actions those we will discussed here. In hibernate we perform all the required action using database without sql procedure insted of we use the POJO class. By the help of the pojo class we perform these type of the action. For the making this type of the action we need to follow the some basic stpe which we have given below:

Step 1. Take a project of java application basically we take like HibernateApplicationUsingSwing as we discussed in our last example.


Step 2. Now All Of First We Need To Create A Package To Store The Our Pojo Class. Go In File Menu Wizard -> Click On New File -> Search Java In The Table And Opposite Side Package -> Put The Name On The Required Place -> Click On Finish.

Step 3. Now We Need To Add The Hibernate Cfg File In Our Project For The Connectivity Of The Database. Go In The File Menu Wizard -> New File -> Click On Hibernate (Search In Table) -> Hibernate Cfg File Click -> Connect The Database -> Finish.

Above code is shown below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_pro</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <mapping resource="r4r/FetchCombo.hbm.xml"/>
    <mapping resource="r4r/Tblstate.hbm.xml"/>
    <mapping resource="r4r/Tblcity.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Step 4. Now We Need To Create A Jframe Form . Go In File Menu Wizard -> New File -> Click On Swing Jframe Form -> Jfrme Form -> Put The Required Name On The Place -> Select To Package -> Click On Finish.

Step 5. Now Create A Table Into The Database.

Above image code is given below:

create table FetchCombo
(
id int not null auto_increment primary key,
fname varchar(50),
address varchar(50),
state varchar(50),
city varchar(50),
pin int(10)
);

Above image code is below:

create table tblcity
(
CITY_NAME varchar(50) DEFAULT NULL primary key,
STATE_NAME varchar(40) DEFAULT NULL
);

Above image code is below:

CREATE TABLE tblstate

(
STATE_NAME varchar(40) not null,
PRIMARY KEY ('STATE_NAME')
);

All both tblstate and tblcity insert code of database query download form below link:


Step 6. Now We Need To Create  A Reverse Eng File. Go In File Menu Wizard -> New File -> Search To Hibernate -> Click On Reverse Eng File -> Select To Table -> Click On Finsh.

Above image code is below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog="hibernate_pro"/>
  <table-filter match-name="FetchCombo"/>
  <table-filter match-name="tblcity"/>
  <table-filter match-name="tblstate"/>
</hibernate-reverse-engineering>

Step 7. Now We Need To Create Pojo Class. Go In File Menu Wizard -> Click On Hibernate -> Click On Pojo Class -> Select To Package -> Click To Finish.

Above image code is below:

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!-- Generated 27 Dec, 2014 3:18:03 PM by Hibernate Tools 4.3.1 -->

<hibernate-mapping>

    <class name="r4r.FetchCombo" table="FetchCombo" catalog="hibernate_pro" optimistic-lock="version">

        <id name="id" type="java.lang.Integer">

            <column name="id" />

            <generator class="identity" />

        </id>

        <property name="fname" type="string">

            <column name="fname" length="50" />

        </property>

        <property name="address" type="string">

            <column name="address" length="50" />

        </property>

        <property name="state" type="string">

            <column name="state" length="50" />

        </property>

        <property name="city" type="string">

            <column name="city" length="50" />

        </property>

        <property name="pin" type="java.lang.Integer">

            <column name="pin" />

        </property>

    </class>

</hibernate-mapping>

Above image code is below:

package r4r;

public class FetchCombo  implements java.io.Serializable {

     private Integer id;

     private String fname;

     private String address;

     private String state;

     private String city;

     private Integer pin;

    public FetchCombo() {

    }

    public FetchCombo(String fname, String address, String state, String city, Integer pin) {

       this.fname = fname;

       this.address = address;

       this.state = state;

       this.city = city;

       this.pin = pin;

    }

       public Integer getId() {

        return this.id;

    }

        public void setId(Integer id) {

        this.id = id;

    }

    public String getFname() {

        return this.fname;

    }

        public void setFname(String fname) {

        this.fname = fname;

    }

    public String getAddress() {

        return this.address;

    }

        public void setAddress(String address) {

        this.address = address;

    }

    public String getState() {

        return this.state;

    }

        public void setState(String state) {

        this.state = state;

    }

    public String getCity() {

        return this.city;

    }

        public void setCity(String city) {

        this.city = city;

    }

    public Integer getPin() {

        return this.pin;

    }

        public void setPin(Integer pin) {

        this.pin = pin;

    }

}

Above image code is below:

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 27 Dec, 2014 3:18:03 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="r4r.Tblcity" table="tblcity" catalog="hibernate_pro" optimistic-lock="version">
        <id name="cityName" type="string">
            <column name="CITY_NAME" length="50" />
            <generator class="assigned" />
        </id>
        <property name="stateName" type="string">
            <column name="STATE_NAME" length="40" />
        </property>
    </class>
</hibernate-mapping>

Above code is shown below:

package r4r;

public class Tblcity  implements java.io.Serializable {

     private String cityName;

     private String stateName;

    public Tblcity() {

    }

    public Tblcity(String cityName) {

        this.cityName = cityName;

    }

    public Tblcity(String cityName, String stateName) {

       this.cityName = cityName;

       this.stateName = stateName;

    }

    public String getCityName() {

        return this.cityName;

    }

    public void setCityName(String cityName) {

        this.cityName = cityName;

    }

    public String getStateName() {

        return this.stateName;

    }

    public void setStateName(String stateName) {

        this.stateName = stateName;

    }

}

Above image code is given below:

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<!-- Generated 27 Dec, 2014 3:18:03 PM by Hibernate Tools 4.3.1 -->

<hibernate-mapping>

    <class name="r4r.Tblstate" table="tblstate" catalog="hibernate_pro" optimistic-lock="version">

        <id name="stateName" type="string">

            <column name="STATE_NAME" length="40" />

            <generator class="assigned" />

        </id>

    </class>

</hibernate-mapping>

Above image code is below:

package r4r;
public class Tblstate  implements java.io.Serializable {
     private String stateName;

    public Tblstate() {
    }
    public Tblstate(String stateName) {
       this.stateName = stateName;
    }
    public String getStateName() {
        return this.stateName;
    }
    public void setStateName(String stateName) {
        this.stateName = stateName;
    }
}

Step 8. Here We Requreid One More Action File To Store The File Action. Create Name Admin Which Hold All Function. Go In File Menu Wizard -> Click On New File -> Click On Java -> Click On Java Class -> Put The Required Name On The Place -> Click On Finish.

Above image code is shown here below:

package r4r;

import java.util.ArrayList;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;

public class Admin 
{
    public static List<String> getState() 
   {
     List<String> a = new ArrayList<String>();   
     try
     {
        SessionFactory sf = new Configuration().configure().buildSessionFactory();
        Session s = sf.openSession();
    Transaction tr = s.beginTransaction();
         Criteria cr = s.createCriteria(r4r.Tblstate.class);
        java.util.List<r4r.Tblstate> ds = cr.list();
        for(r4r.Tblstate dd : ds)
        {
        a.add(dd.getStateName());   
         }   
     }catch(Exception ex) { a.add(ex.getMessage()); }
     return a;
   }
   public static List<String> getCity(String st) 
   {
     List<String> a = new ArrayList<String>();   
     try
     {
         SessionFactory sf = new Configuration().configure().buildSessionFactory();
         Session s = sf.openSession();
         Transaction tr = s.beginTransaction();
         Criteria cr = s.createCriteria(r4r.Tblcity.class).add(Restrictions.eq( "stateName", st));
        java.util.List<r4r.Tblcity> ds = cr.list();
        for(r4r.Tblcity dd : ds)
        {
        a.add(dd.getCityName());   
         }
     }catch(Exception ex) { a.add(ex.getMessage()); }
     return a;
   }
    
}

Step 8. Now change the code of the InsertData form.

Above selected code is given below:

public class InsetData extends javax.swing.JFrame {
    public InsetData() {
        initComponents();
        List<String> a = r4r.Admin.getState();
           for(String s : a)
           state.addItem(s); 
    }
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        fname = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        address = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        state = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        city = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        pin = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("First Name");

        fname.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fnameActionPerformed(evt);
            }
        });

        jLabel2.setText("Address");

        jLabel3.setText("State");

        state.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--Select State--" }));
        state.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                stateActionPerformed(evt);
            }
        });

        jLabel4.setText("City");

        city.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--Select City--" }));
        city.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cityActionPerformed(evt);
            }
        });

        jLabel5.setText("Pin");

        jButton1.setText("Submit");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(213, 213, 213)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1))
                .addGap(57, 57, 57)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(fname)
                        .addComponent(address)
                        .addComponent(state, 0, 183, Short.MAX_VALUE)
                        .addComponent(city, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(pin)))
                .addContainerGap(288, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(64, 64, 64)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(fname, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(address, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(state, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(16, 16, 16)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(city, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(pin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(49, 49, 49)
                .addComponent(jButton1)
                .addContainerGap(94, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void fnameActionPerformed(java.awt.event.ActionEvent evt) {                                      
        // TODO add your handling code here:
    }                                     

    private void stateActionPerformed(java.awt.event.ActionEvent evt) {                                      

        city.removeAllItems();
        System.out.print("ttttt"+state.getSelectedItem().toString());
        List<String> a = r4r.Admin.getCity(state.getSelectedItem().toString());
        for(String s : a){
            System.out.print("ttttt");
            city.addItem(s); }
    }                                     

    private void cityActionPerformed(java.awt.event.ActionEvent evt) {                                     

    }                                    

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
       SessionFactory sf = new Configuration().configure().buildSessionFactory();
        Session s = sf.openSession();
        Transaction tr = s.beginTransaction();
        FetchCombo fc = new FetchCombo(fname.getText(), address.getText(), state.getSelectedItem().toString(), city.getSelectedItem().toString(), Integer.parseInt(pin.getText()));
        JOptionPane.showMessageDialog(this, "One Record Inserted");
        s.save(fc);
        
        tr.commit();
        s.close();
        s.clear();
    } 

Step 9. Now build and run the application.

Now check the database table is record inserted or not. which is given below:




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!