VietTuts

Tự Học Lập Trình Online

  • Home
  • Java
  • Servlet
  • JSP
  • Struts2
  • Hibernate
  • Spring
  • MyBatis
  • Java WS
  • C
  • C++
  • C#
  • Python
  • PHP
  • Excel
  • VBA
  • Web
    • JavaScript
    • JQUERY
    • JSON
    • AJAX
    • CSS
    • HTML
    • HTML5
    • Node.js
    • Angular 7
  • SQL
    • MySQL
    • SQL Server
  • Misc
    • Eclipse
    • Phần mềm tiện ích
    • Cấu trúc DL&GT
    • Selenium Test

Hibernate Tuts

ORM là gì? Hibernate là gì? Hibernate - Kiến trúc Hibernate - Môi trường Hibernate - File cấu hình XML Hibernate - File Mapping Hibernate - Thuộc tính type Hibernate - Lớp persistent Hibernate - Sessions Hibernate - example Hibernate - O/R mapping Hibernate - Annotations Hibernate - Query Language Hibernate - Criteria Queries Hibernate - Native SQL Hibernate - Bộ nhớ cache Hibernate - Batch processing Hibernate - Interceptors

Hibernate với các ví dụ

Hibernate - many-to-one relationship với MySQL trên Eclipse Hibernate - one-to-one relationship với MySQL trên Eclipse Hibernate - one-to-many relationship với MySQL trên Eclipse Hibernate - many-to-many relationship với MySQL trên Eclipse

Hibernate Tool

Cài đặt Hibernate/Jboss Tools trong Eclipse IDE Tạo Hibernate Configuration (hibernate.cfg.xml) với Hibernate Tools Sử dụng Hibernate Tools tạo các file mapping và annotation

Hibernate 5 Examples

Ví dụ Hibernate 5 XML Mapping – MySQL Ví dụ Hibernate 5 XML Mapping – SQLServer 2017 Ví dụ Hibernate 5 Annotation Mapping – MySQL Ví dụ Hibernate 5 Annotation Mapping – SQLServer 2017

Hibernate 4 Examples

Ví dụ Hibernate 4 XML Mapping – MySQL Ví dụ Hibernate 4 XML Mapping – SQLServer 2017 Ví dụ Hibernate 4 Annotation Mapping – MySQL Ví dụ Hibernate 4 Annotation Mapping – SQLServer 2017

Hibernate 3 Examples

Ví dụ Hibernate 3 XML Mapping – MySQL Ví dụ Hibernate 3 XML Mapping – SQLServer 2017 Ví dụ Hibernate 3 Annotation Mapping – MySQL Ví dụ Hibernate 3 Annotation Mapping – SQLServer 2017

Phỏng vấn Hibernate

List câu hỏi phỏng vấn Hibernate
1 / 3
❮ ❯

Ví dụ Hibernate 5 XML Mapping - SQLServer 2017


Java
Spring

This example apply following technologies:

  • Eclipse Oxygen 4.7
  • SQLServer 2017 Express
  • JDK 1.8
  • Hibernate 5.2.12.Final

Nội dung chính

  • Hibernate 5 XML Mapping Project Structure
  • Create Hibernate 5 XML Mapping - SQLServer 2017 Example
    • 1. Create project "hibernate5-xml-example2"
    • 2. Create table testdb.Employee
    • 3. Create entity class
    • 4. Create XML mapping file
    • 5. Create hibernate configuration file
    • 6. Build SessionFactory object
    • 7. Create application class

Hibernate 5 XML Mapping Project Structure

Hibernate 5 XML Mapping - SQLServer 2017 Example

Create Hibernate 5 XML Mapping - SQLServer 2017 Example

1. Create project "hibernate5-xml-example2"

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>5.2.12.Final</version>
    </dependency>

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

    <dependency>
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <version>6.1.0.jre8</version>
    </dependency>
</dependencies>

2. Create table testdb.Employee

Use testdb;

create table EMPLOYEE (
   id INT NOT NULL IDENTITY(1,1),
   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. It has properties, getters and setters for respective properties.

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

Craete XML mapping file to map Java POJO class (com.realtut.entity.Employee) to database table (employee).

File: Employee.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!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">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="identity" />
        </id>
        <property name="firstName" type="string">
            <column length="20" name="first_name" />
        </property>
        <property name="lastName" type="string">
            <column length="20" name="last_name" />
        </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 PUBLIC
  "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
  "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">
            com.microsoft.sqlserver.jdbc.SQLServerDriver
        </property>
        <property name="hibernate.connection.url">
            jdbc:sqlserver://localhost:1433;databaseName=testdb;
        </property>
        <property name="hibernate.connection.username">
            sa
        </property>
        <property name="hibernate.connection.password">
            1234567890
        </property>

        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQLDialect
        </property>

        <!-- Show all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- List mapping XML files -->
        <mapping resource="Employee.hbm.xml" />
    </session-factory>
</hibernate-configuration>

6. Build SessionFactory object

File: HibernateUtil.java

package com.realtut.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    public static SessionFactory getSessionFactory() {
        SessionFactory sessionFactory = null;
        try {
            Configuration configuration = new Configuration();
            sessionFactory = configuration.configure().buildSessionFactory();
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
        return sessionFactory;
    }
}

7. 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 com.realtut.entity.Employee;
import com.realtut.utils.HibernateUtil;

public class ManageEmployee {
    private static SessionFactory factory;

    public static void main(String[] args) {
        // get session factory
        factory = HibernateUtil.getSessionFactory();

        // create manageEmployee object
        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();
        try {
            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());
            }
        } catch (HibernateException e) {
            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

Dowload Source Code

Download Now!


Java
Spring

Recent Updates

Sắp Tết 2024 Rồi! - Còn bao nhiêu ngày nữa là đến tết 2024?Ví dụ Hibernate 3 XML Mapping - SQLServer 2017Ví dụ Hibernate 4 Annotation Mapping - MySQLVí dụ Hibernate 4 Annotation Mapping - SQLServer 2017Ví dụ Hibernate 4 XML Mapping - MySQLVí dụ Hibernate 4 XML Mapping - SQLServer 2017Ví dụ Hibernate 5 Annotation Mapping - MySQLVí dụ Hibernate 5 Annotation Mapping - SQLServer 2017Ví dụ Hibernate 5 XML Mapping - MySQLVí dụ Hibernate 5 XML Mapping - SQLServer 2017Ví dụ về HibernateSự khác nhau giữa MyBatis và HibernateList câu hỏi phỏng vấn Hibernate

VietTuts on facebook

Học Lập Trình Online Miễn Phí - VietTuts.Vn
Danh Sách Bài Học

Học Java | Hibernate | Spring
Học Excel | Excel VBA
Học Servlet | JSP | Struts2
Học C | C++ | C#
Học Python
Học SQL

Bài Tập Có Lời Giải

Bài tập Java
Bài tập C
Bài tập C++
Bài tập C#
Bài tập Python
Ví dụ Excel VBA

Câu Hỏi Phỏng Vấn

201 câu hỏi phỏng vấn java
25 câu hỏi phỏng vấn servlet
75 câu hỏi phỏng vấn jsp
52 câu hỏi phỏng vấn Hibernate
70 câu hỏi phỏng vấn Spring
57 câu hỏi phỏng vấn SQL

Scroll back to top

Copyright © 2016 VietTuts.Vn all rights reserved. | Liên hệ | Chính sách - riêng tư | sitemap.html | sitemap_index.xml