开发框架 Hibernate

  Hibernate 是一个开放源代码的对象关系映射框架,它对 JDBC 进行了非常轻量级的对象封装,它将 POJO 与数据库表建立映射关系,是一个全自动的 ORM 框架,Hibernate 可以自动生成 SQL 语句,自动执行,使得 Java 程序员可以熟练地使用对象编程思维来操纵数据库。

Hibernate 开发流程

  Hibernate 首先通过配置文件 cfg.xml 初始化数据库,创建 SessionFactory,进而得到 session 也就是一个数据库连接。cfg 文件中包括数据库驱动、URL、数据库名称以及密码等等参数,最重要的是将表或者视图的 hbm 文件写入 cfg 文件,否则是无法使用 Hibernate 服务的。当用户操作数据库表或视图的时候,hibernate 加载此表的 Hibernate mapping 文件,也就是 hbm.xml 文件。Hbm 文件主要是映射数据库表与持久化类 POJO。通过 hbm 文件可以将实体对象与数据库表或者视图对应,从而间接的操作数据库表或者视图。

../../_images/Hibernate.png

图 2.2.1 Hibernate 的使用原理

Hibernate 工程搭建

使用 Hibernate 来进行项目开发有以下两种方法可以完成环境的搭建:

  1. 在项目创建完成之后,在/lib 的目录下导入 Hibernate 的核心 jar 包以及 hibernatexxdialect.jar 的方言包。

  2. 使用 Maven 工具来管理 jar 包,在下载 unvdb 数据库后从数据库 Interface/JDBC 路径拉取 unvdb 的 JDBC 驱动 jar 包,通过 mvn install:install-file -DgroupId=com.unvdb -DartifactId=unvdb-jdbc -Dversion=42.7.3 -Dpackaging=jar -Dfile=unvdb-jdbc-42.7.3.jar 将 JDBC 驱动导入到本地的 Maven 仓库。

  3. 指令将 jar 包导入到本地 maven 仓库后,即可通过修改 pom.xml 文件的相关配置来导入 Hibernate 的核心 jar 包以及 hibernatexxdialect.jar 方言包。

Hibernate 的配置文件说明

定义 hibernate 配置文件,根据用户选择更改以下配置文件。

a. 在 pom.xml 中引入以下依赖:

  <!-- unvdb -->
  <dependency>
      <groupId>com.unvdb</groupId>
      <artifactId>unvdb-jdbc</artifactId>
      <version>42.7.3</version>
  </dependency>
  <!-- druid -->
  <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>1.1.21</version>
  </dependency>
  <!-- hibernate -->
  <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-data-jpa</artifactId>
  </dependency>
  <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-core</artifactId>
  </dependency>
  <!-- 配置国密所需依赖 -->
  <dependency>
      <groupId>org.openeuler</groupId>
      <artifactId>bgmprovider</artifactId>
      <version>1.1.3</version>
  </dependency>

b.在application.properties中修改 Hibernate 环境配置:

spring:
  datasource:
    username: 登录名
    password: 登录密码
    url: jdbc:unvdb://localhost:5678/test
    driver-class-name: com.unvdb.Driver
  # 只返回不为 null 的数据
  jackson:
    default-property-inclusion: non_null
  jpa:
    database: POSTGRESQL
    show-sql: true
  hibernate:
    ddl-auto: update
    properties:
      hibernate:
        format_sql: true
        dialect: org.hibernate.dialect.PostgreSQLDialect
        new_generator_mappings: false
        ddl_auto: update
        show-sql: true
        database-platform: org.hibernate.dialect.PostgreSQLDialect

Hibernate 项目示例

a.创建实体类,在项目中创建一个或多个实体类,并使用JPA注解来映射数据库表,例如:

import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;

@Data
@Entity
@Table(name = "users")
public class User implements Serializable {
    private static final long serialVersionUID = 18L;

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;
}

b.创建数据访问层(Repository)创建一个接口来继承JpaRepository或CrudRepository,这样你就可以使用SpringDataJPA提供的方法来执行基本的CRUD操作。例如:

import com.example.hibernate.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserDao extends JpaRepository<User, Integer> {
}

c. 创建服务层(service 层)在服务层中,你可以编写业务逻辑,并调用数据访问层的方法来执行数据库操作。例如:

import com.example.hibernate.entity.User;
import java.util.List;
public interface UserService {
  /**
  * 查询全部用户
  * @return List<User>
  */
  List<User> selectAll();
}
import com.example.hibernate.dao.UserDao;
import com.example.hibernate.entity.User;
import com.example.hibernate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    private final UserDao userDao;

    @Autowired
    public UserServiceImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public List<User> selectAll() {
        return userDao.findAll();
    }
}

d.创建控制器层(Controller层)在控制器层中,你可以编写RESTful API或Web页面控制器,以处理来自客户端的请求,并调用服务层的方法来执行业务逻辑。例如:

import com.example.hibernate.entity.User;
import com.example.hibernate.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;

@RestController
@RequestMapping(path = "/users", produces = "application/json;charset=utf-8")
public class UserController {
    private final UserService userService;

    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @RequestMapping(value = "/selectAll", method = RequestMethod.GET)
    List<User> selectAll() {
        return userService.selectAll();
    }
}

如想对示例进行测试,后续可自行创建Test类进行对应的CRUD测试。

Hibernate 注意事项

a. 根据数据库类型选择合适的 Hibernate 方言,以确保 SQL 语句正确生成。

b. 注解使用:确保实体类使用正确的 JPA 注解进行映射,如@Entity@Table@Id@GeneratedValue 等。这些注解用于告诉 Hibernate 如何将实体类映射到数据库表及其字段上。

c. 关系映射:如果实体类之间存在关联关系(如一对一、一对多、多对多等),需要使用相应的 JPA 注解(如@OneToOne@OneToMany@ManyToMany)来正确映射这些关系。