Hibernate

adplus-dvertising
Inserting Data into More than One table in the database with Hibernate Using Swing
Previous Home Next

Insert data into database using Swing in Hibernate: In the Hibernate we can create a application through the swing. Hibernate can work with the swing also. As we shown in the given below example. For creating the application we need to follow some basic step which is given below:

Step 1. First of all we need to create a java application using NetBeans IDE, Appache Tomcat and MySql server. For creating a application we open the NetBeans and click on File Menu Wizard -> click on New -> search the java web click on it -> next -> put the name of the application on the required field -> click on finish. (as given in the below images)

Step 2. Now we need to create a package.(as shown in image). Go in File menu wizard -> click on new file -> java -> package -> put the name -> finish.

Step 3. Now we need to create a hibernate.cfg.xml file. Go in File Menu Wizard -> new file -> Hibernate -> hibernate.cfg.xml -> make to the connection with the database (Hibernate_pro is the pre created connection so never be confused) -> finish. After the creation the hibernate.cfg.xml file we see the below given situation.

hibernate cfg code


 <?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?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
  </session-factory>
</hibernate-configuration>

Step 4. Now create a JFrame file. For this Go in File Menu Wizard -> new file -> swing gui forms -> JFrame Form -> put the name of the file on the required field -> select the package -> click on finish.

Step 5. Now create the Field on the Form which we want to create. For this Go in Window -> IDE Tools -> click on Palete and now drag which item we want to show on the our application. Form will show (as given below in the image). After the drag element we found the Form as given in the image which is shown below:

Step 6. Now we need to run the application for checking the code is properly working or not. For this go in run -> click on run file.

Step 7. Put the each text name like as first_name, last_name, address by the going in the nevigation bar. It will help to take the data into the database. Because which text will be inserted into the specific text box that will properly workable.

Step 8. Now create table in the database which we create the connection in the hibernate.cfg.xml.


(a) create table InserSwingData
    (
       id int not null primary key auto_increment,
       first_name varchar(40),
       last_name varchar(40),
       address varchar(40)
     )


(b) create table PersonalInformation
    (
      id int not null primary key auto_increment,
      address varchar(40),
      phone int(12)
     )

Step 9. Now we need to create a reverse engeneering file. go in file menu wizard -> new file -> hibernate -> hibernate reverse engering file -> select the table which we created into the database. add and then finish.

hibernate revenge file code


<?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="PersonalInformation"/>
  <table-filter match-name="InserSwingData"/>
</hibernate-reverse-engineering>

Step 10. Now we need to create a POJO class. for this go in file menu wizard -> new file -> hibernate -> hibernate pojo class -> select the package -> finish. Below image show that the all pojo class and code is below of the image which is shown in the image.


<?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 10 Dec, 2014 8:50:00 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="r4r.InserSwingData" table="InserSwingData" catalog="hibernate_pro" optimistic-lock="version">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="firstName" type="string">
            <column name="first_name" length="40" />
        </property>
        <property name="lastName" type="string">
            <column name="last_name" length="40" />
        </property>
        <property name="address" type="string">
            <column name="address" length="40" />
        </property>
    </class>
</hibernate-mapping>


package r4r;
// Generated 10 Dec, 2014 8:49:59 PM by Hibernate Tools 4.3.1
/**
 * InserSwingData generated by hbm2java
 */
public class InserSwingData  implements java.io.Serializable {
     private Integer id;
     private String firstName;
     private String lastName;
     private String address;

    public InserSwingData() {
    }

    public InserSwingData(String firstName, String lastName, String address) {
       this.firstName = firstName;
       this.lastName = lastName;
       this.address = address;
    }
   
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getFirstName() {
        return this.firstName;
    }
    
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return this.lastName;
    }
    
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public String getAddress() {
        return this.address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }

}

PersonalInformation.hbm.xml


 <?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 10 Dec, 2014 9:27:12 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
    <class name="r4r.PersonalInformation" table="PersonalInformation" catalog="hibernate_pro" optimistic-lock="version">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="address" type="string">
            <column name="address" length="40" />
        </property>
        <property name="phone" type="java.lang.Integer">
            <column name="phone" />
        </property>
    </class>
</hibernate-mapping>


 package r4r;
public class PersonalInformation  implements java.io.Serializable {
     private Integer id;
     private String address;
     private Integer phone;

    public PersonalInformation() {
    }

    public PersonalInformation(String address, Integer phone) {
       this.address = address;
       this.phone = phone;
    }
   
    public Integer getId() {
        return this.id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    public String getAddress() {
        return this.address;
    }
    
    public void setAddress(String address) {
        this.address = address;
    }
    public Integer getPhone() {
        return this.phone;
    }
    
    public void setPhone(Integer phone) {
        this.phone = phone;
    }

}

Step 11. Now we need to create a hibernate utill class for making the session in the hibernate. go in file menu wizard -> new file -> hibernate -> hibernate util -> put the required name -> select the package -> finish.

Step 11. Now we need to create a hibernate utill class for making the session in the hibernate. go in file menu wizard -> new file -> hibernate -> hibernate util -> put the required name -> select the package -> finish. Which code is shown in the image that is given below of the hibernate util file.



package r4r;

import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;

public class HibernateUtil {

    private static final SessionFactory sessionFactory;
    
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }
    
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Step 12. Now edit into the JFrame file for making the aciton. For making the action on submit button right click on the submit button -> event -> action -> action performed.


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
          SessionFactory sf = new Configuration().configure().buildSessionFactory();
        Session s = sf.openSession();
        Transaction tr = s.beginTransaction();
        InserSwingData isd = new InserSwingData(first_name.getText(), last_name.getText(), address.getText());
        PersonalInformation pr = new PersonalInformation(address.getText(), Integer.parseInt(phone.getText()));
        JOptionPane.showMessageDialog(this, "One Record Inserted");
        s.save(isd);
        s.save(pr);
        tr.commit();
        s.close();
        s.clear();
    } 

Step 13. Now run the application

Previous Home Next