20/07/2019, 10:12

Ví dụ Hibernate 3 XML Mapping – MySQL

Java This example apply following technologies: Eclipse Oxygen 4.7 MySQL 10.1.29-MariaDB (from xampp-win32-7.2.0-0-VC15-installer) JDK 1.8 Hibernate 3.6.3 Nội dung chính: Hibernate 3 XML Mapping Project Structure Create Hibernate 3 XML ...

Java

This example apply following technologies:

  • Eclipse Oxygen 4.7
  • MySQL 10.1.29-MariaDB (from xampp-win32-7.2.0-0-VC15-installer)
  • JDK 1.8
  • Hibernate 3.6.3

Nội dung chính:

  • Hibernate 3 XML Mapping Project Structure
  • Create Hibernate 3 XML Mapping – MySQL Example
    • 1. Create project “hibernate3-xml-example”
    • 2. Create table testdb.Employee
    • 3. Create entity class
    • 4. Create XML mapping file
    • 5. Create hibernate configuration file
    • 6. Create application class

Hibernate 3 XML Mapping Project Structure

Hibernate 3 XML Mapping - MySQL Example

Create Hibernate 3 XML Mapping – MySQL Example

1. Create project “hibernate3-xml-example”

You can refer to tutorial how to create maven project in Eclipse?.

Update pom.xml file:

<dependencies>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>3.6.3.Final</version>
    </dependency>

    <dependency>
        <groupId>javassist</groupId>
        <artifactId>javassist</artifactId>
        <version>3.12.1.GA</version>
    </dependency>

    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.20</version>
    </dependency>
</dependencies>

2. Create table testdb.Employee

create table testdb.EMPLOYEE (
   id INT NOT NULL auto_increment,
   first_name VARCHAR(20) default NULL,
   last_name  VARCHAR(20) default NULL,
   salary     INT  default NULL,
   PRIMARY KEY (id)
);

3. Create entity class

Create Employee.java as a POJO class.

File: Employee.java

package com.realtut.entity;

public class Employee implements java.io.Serializable {
    private Integer id;
    private String firstName;
    private String lastName;
    private Integer salary;

    public Employee() {
    }

    public Employee(String firstName, String lastName, Integer salary) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.salary = salary;
    }

    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 Integer getSalary() {
        return this.salary;
    }

    public void setSalary(Integer salary) {
        this.salary = salary;
    }
}

4. Create XML mapping file

File: Employee.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">
<hibernate-mapping>
    <class name="com.realtut.entity.Employee" table="employee" catalog="testdb">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="firstName" type="string">
            <column name="first_name" length="20" />
        </property>
        <property name="lastName" type="string">
            <column name="last_name" length="20" />
        </property>
        <property name="salary" type="java.lang.Integer">
            <column name="salary" />
        </property>
    </class>
</hibernate-mapping>

5. Create hibernate configuration file

File: hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM 
"http://www.hibernate.org/dtd/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/testdb
        </property>
        <property name="hibernate.connection.username">
            root
        </property>
        <property name="hibernate.connection.password">
            1234567890
        </property>

         
        <mapping resource="Employee.hbm.xml" />

    </session-factory>
</hibernate-configuration>

6. Create application class

Finally, we will create the application class to run by the main() method. There are some methods to perform CRUD operations (create, retrive, update, delete).

File: ManageEmployee.java

package com.realtut;

import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import com.realtut.entity.Employee;

public class ManageEmployee {
    private static SessionFactory factory;

    public static void main(String[] args) {
        try {
            factory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
        ManageEmployee manageEmployee = new ManageEmployee();

        // Add few employee records in database
        Integer empID1 = manageEmployee.addEmployee("David", "Bishop", 1000);
        Integer empID2 = manageEmployee.addEmployee("Chris", "Ali", 5000);
        Integer empID3 = manageEmployee.addEmployee("John", "Vector", 10000);

        // List down all the employees
        System.out.println("List down all the employees:");
        manageEmployee.listEmployees();

        // Update employee's records
        manageEmployee.updateEmployee(empID1, 5000);

        // Delete an employee from the database
        manageEmployee.deleteEmployee(empID2);

        // List down new list of the employees
        System.out.println("List down new list of the employees:");
        manageEmployee.listEmployees();
    }

    // Method to CREATE an employee in the database
    public Integer addEmployee(String fname, String lname, int salary) {
        Session session = factory.openSession();
        Transaction tx = null;
        Integer employeeID = null;
        try {
            tx = session.beginTransaction();
            Employee employee = new Employee(fname, lname, salary);
            employeeID = (Integer) session.save(employee);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
        return employeeID;
    }

    // Method to READ all the employees
    public void listEmployees() {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            List employees = session.createQuery("FROM Employee").list();
            for (Iterator iterator = employees.iterator(); iterator.hasNext();) {
                Employee employee = (Employee) iterator.next();
                System.out.print("First Name: " + employee.getFirstName());
                System.out.print("  Last Name: " + employee.getLastName());
                System.out.println("  Salary: " + employee.getSalary());
            }
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    // Method to UPDATE salary for an employee
    public void updateEmployee(Integer EmployeeID, int salary) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Employee employee = (Employee) session.get(Employee.class, EmployeeID);
            employee.setSalary(salary);
            session.update(employee);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }

    // Method to DELETE an employee from the records
    public void deleteEmployee(Integer EmployeeID) {
        Session session = factory.openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();
            Employee employee = (Employee) session.get(Employee.class, EmployeeID);
            session.delete(employee);
            tx.commit();
        } catch (HibernateException e) {
            if (tx != null)
                tx.rollback();
            e.printStackTrace();
        } finally {
            session.close();
        }
    }
}

Output:

List down all the employees:
First Name: David  Last Name: Bishop  Salary: 1000
First Name: Chris  Last Name: Ali  Salary: 5000
First Name: John  Last Name: Vector  Salary: 10000
List down new list of the employees:
First Name: David  Last Name: Bishop  Salary: 5000
First Name: John  Last Name: Vector  Salary: 10000
Java
0