[Hibernate] 基本增删查改

Posted TonyYPZhang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[Hibernate] 基本增删查改相关的知识,希望对你有一定的参考价值。

本文记录,Java 应用通过 Hibernate 对数据库 mysql 进行基本的增删改查操作,即CRUD。

 

本例子的目录结构如下

hibernate.cfg.xml 存储数据库信息,如数据库类型,账号密码,数据库名称

Empoyee.hbm.xml,声明 java 简单对象和数据库表结构的对应关系

Employee.java,java 简单对象,用于声明数据结构

ManageEmployee,管理 Employee,并对外提供操作 Employee 对象数据的接口。

App.java,演示本案例

 

 

代码详情

在数据库中,创建表结构

create table 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)
);

 

创建简单对象类, POJO(Plain Old Java Object)。在 Java 中定义 Employee 的数据结构。

package tony.hibernateTest;

public class Employee {
    private int id;
    private String firstName;
    private String lastName;
    private int salary;
    
    public Employee(){
    }
    public Employee(String fname, String lname, int salary){
        this.firstName = fname;
        this.lastName = lname;
        this.salary = salary;
    }
    
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
}

 

在 xml 文件中,将 java 的简单类 Employee 和数据库 employee 的表结构建立映射关系。

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
 "-//Hibernate/Hibernate Mapping DTD//EN"
 "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> 
 
 <hibernate-mapping>
     <class name="tony.hibernateTest.Employee" table="employee">
       <id name="id" type="int" column="id">         </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
           
     </class>
 
 </hibernate-mapping>

 

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>

   <!-- Assume test is the database name -->
   <property name="hibernate.connection.url">
      jdbc:mysql://localhost/hibernateTest
   </property>
   <property name="hibernate.connection.username">
      username
   </property>
   <property name="hibernate.connection.password">
      password
   </property>

   <!-- List of XML mapping files -->
   <mapping resource="Employee.hbm.xml"/>

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

 

ManageEmployee,Employee 的操作工具类。对业务层提供操作 Employee 的接口。

 

package tony.hibernateTest;

import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class ManageEmployee {
    
    private static SessionFactory factory;
    {
        factory = new Configuration().configure().buildSessionFactory();
    }
    
    /**
     * Add an employee record into database.
     * @param fname
     * @param lname
     * @param salary
     * @return
     */
    public Integer addEmployee( String fname, String lname, int salary ){
        
        Session session = factory.openSession();
        Transaction tx = null;
        Integer employeeId = null;
        
        tx = session.beginTransaction();
        
        Employee employee = new Employee(fname, lname, salary);
        employeeId = (Integer)session.save(employee);
        tx.commit();        
        
        return employeeId;
    }
    
    public void listEmployees(){
        Session session = factory.openSession();
        Transaction tx = null;
        
        tx = session.beginTransaction();
        List<Employee> employees = session.createQuery("FROM Employee").list();
        for (Employee ee : employees){
            System.out.println(ee.getId() + ", " + ee.getFirstName() + ", " + ee.getLastName() + ", " + ee.getSalary());
        }
        tx.commit();        
    }
    
    public List<Employee> getAllEmployees(){
        Session session = factory.openSession();
        Transaction tx = null;
        
        tx = session.beginTransaction();
        List<Employee> employees = session.createQuery("FROM Employee").list();
        tx.commit();    
        return employees;
    }

    
    /**
     * update salary of the specified employee in database
     * @param employeeId
     * @param salary
     */
    public void updateEmployee(Integer employeeId, int salary){
        Session session = factory.openSession();
        Transaction tx = null;
        
        tx = session.beginTransaction();
        Employee ee = session.get(Employee.class, employeeId);
        ee.setSalary(salary);
        tx.commit();
    }
    
    public void deleteEmployee(Integer employeeId){
        Session session = factory.openSession();
        Transaction tx = null;
        
        tx = session.beginTransaction();
        Employee ee = session.get(Employee.class, employeeId);
        session.delete(ee);
        tx.commit();
    }    
}

 

App.java,Hibernate 增删该查功能演示类。创建 employee 的功能类 ManageEmployee,通过 ManageEmployee 提供的接口,进行增加、更新、删除 MySQL 中数据。

package tony.hibernateTest;

import java.util.List;

public class App 
{
    public static void main( String[] args )
    {        
        ManageEmployee me = new ManageEmployee();
        int empId1 = me.addEmployee("aa", "bb", 11);
        int empId2 = me.addEmployee("cc", "ff", 22);        
        
        List<Employee> employees = me.getAllEmployees();
        
        Employee firstEmp = employees.get(0);
        me.updateEmployee(firstEmp.getId(), firstEmp.getSalary() + 10);

        Employee lastEmp = employees.get(employees.size() - 2);
        me.deleteEmployee(lastEmp.getId());
        
        me.listEmployees();
    }
}

 

在 pom.xml 中,声明使用到的依赖,通过 maven 进行加载。

    <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.3.Final</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.6</version>
    </dependency>

 

参考资料

Hibernate - Examples, tutorialspoint

 

以上是关于[Hibernate] 基本增删查改的主要内容,如果未能解决你的问题,请参考以下文章

实现基本的增删查改功能

数据结构:链表实现增删查改的基本功能内含详细代码,建议收藏

单链表的增删查改等基本操作C++实现

顺序表的基本操作——增删查改

python 实现mysql增删查改

EF基本操作增删查改分页,join……等