第11章 SpringBoot集成Jpa

JPA(Java Persistence API)是Sun官方提出的Java持久层规范。JPA的出现主要是为了简化持久化开发工作和整合ORM技术。JPA的主要设计者是Hibernate的设计者。JPA只是一种规范,不是产品。Hibernate3.2+ 提供了JPA的实现。Spirng Data JPA在JPA规范下提供了持久层的实现。Spirng Data对持久层封装的很好,代码写起来更加简洁。Spring Data项目是Spring 的一个子项目,旨在统一简化各类型持久化存储。Spring Data中包括了对JDBC,JPA,MongoDB,Redis,Neo4j,Hadoop等等的支持。

ORM(Object-Relational Mapping, 对象关系映射),是一种面向对象编程语言中的对象和数据库中的数据之间的映射。JPA(Java Persistence API,Java持久层API) 是Sun公司定义的一套基于ORM的接口规范,用于给Java程序操作数据库。JPA 通过注解描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中 。很多ORM框架实现了JPA规范,其中最有名的有Hibernate。JPA 和 Hibernate 的关系就像 JDBC 和 JDBC 驱动的关系。

Spirng Data JPA是Spring基于ORM框架,JPA规范封装的一套JPA应用框架,可使开发人员用极简的代码实现对数据库的访问和操作。它提供了包括增删改查在内的常用功能。spring-boot-starter-data-jpa是Spring Boot集成Spring Data JPA的依赖。在使用Spring Boot集成Spring Data JPA开发的时候,通常采用注解方法。

首先,我们新建一个“SprinBootJpaDemo”的Maven工程

然后我们修改编码格式以及Maven仓库地址,我们省略这个过程了。

接下来,我们修改 “pom.xml” 文件,增加web和jpa依赖,

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.demo</groupId>
    <artifactId>SprinBootJpaDemo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.13</version>
        <relativePath/>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.49</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.8</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.16</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.7.18</version>
            </plugin>
        </plugins>
    </build>
    
</project>

接下来,我们创建 Appliaction 入口类文件

package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

    public static void main(String[] args) {

        SpringApplication.run(Application.class, args);
    }
}

接下来,我们要创建 application.properties 中配置数据源

spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf-8&useSSL=false&autoReconnect=true
spring.datasource.username = root
spring.datasource.password = 123456

关于“student”数据库的内容请参考: 第04章 SQL语句-优快云博客

首先编写一个 StudentInfoEntity 学生实体类

package com.demo.entity;

import lombok.Data;
import javax.persistence.*;

@Data
@Entity
@Table(name = "student_info")
public class StudentInfoEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "stu_id")
    private long stuId;

    @Column(name = "class_id")
    private int classId;

    @Column(name = "stu_name")
    private String stuName;

    @Column(name = "stu_age")
    private String stuAge;

    @Column(name = "stu_sex")
    private boolean stuSex;

    @Column(name = "add_time")
    private String addTime;
    
}

这个与 “MyBatisPlus” 十分的相似,因为他们都源于ORM映射的思想。

这里需要介绍上面的几个注解:

@Entity: 声明当前类是一个实体类
@Table: 配置实体类和表的映射关系,name就是表名
@Column: 映射数据库表中的字段,就是类变量绑定表字段,name就是字段名
@Id: 声明当前字段变量为主键
@GeneratedValue(strategy = GenerationType.IDENTITY): 声明当前字段变量为自增

当然,还有更多的注解,这里不再详细介绍。 这里还需要注意两个点,其一是注解引入包必须是javax.persistence下的,其二就是主键字段变量的类型是long,即使数据库表字段是integer类型,这里也要是long。 接下来我们我们再创建一个 StuentInfoRepository 数据库持久接口来使用上面的实体类。

package com.demo.repository;

import com.demo.entity.StudentInfoEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StuentInfoRepository extends JpaRepository<StudentInfoEntity, Long> {

}

这个数据库持久对象实质就是一个接口,然后就能操作数据库表记录了。虽然我们只定义了数据实体类以及一个空接口对象,甚至一句代码或一句SQL语句都没有写,就基本实现数据库表的增删改查操作了。这主要归功于我们继承的JpaRepository接口。

JpaRepository是 Spring Boot Data JPA 提供的非常强大的基础接口。 JpaRepository继承了接口PagingAndSortingRepository和QueryByExampleExecutor。而PagingAndSortingRepository又继承CrudRepository。因此,JpaRepository接口同时拥有了基本CRUD功能以及分页功能。当我们需要定义自己的Repository接口的时候,我们可以直接继承JpaRepository,从而获得Spring Boot Data JPA为我们内置的多种基本数据操作方法。

我们简单介绍 CrudRepository 提供的方法:

// 保存一个实体。
<S extends T> S save(S entity);

// 保存提供的所有实体。
<S extends T> Iterable<S> saveAll(Iterable<S> entities);

// 根据id查询对应的实体。
Optional<T> findById(ID id);

// 根据id查询对应的实体是否存在。
boolean existsById(ID id);

// 查询所有的实体。
Iterable<T> findAll();

// 根据给定的id集合查询所有对应的实体,返回实体集合。
Iterable<T> findAllById(Iterable<ID> ids);

// 统计现存实体的个数。
long count();

// 根据id删除对应的实体。
void deleteById(ID id);

// 删除给定的实体。
void delete(T entity);

// 删除给定的实体集合。
void deleteAll(Iterable<? extends T> entities);

// 删除所有的实体。
void deleteAll();

备注:新增和修改都调用的save()方法,如何什么区分是insert还是update呢?主要是主键id有没有赋值判断:id有值为update,id无值为insert。并且还需要根据ID查询方法findById(Id)查询得到实体对象,再对实体对象进行属性赋值修改,最后再进行save,才能实现该Id对应记录的修改,否则会进行新增。我们简单介绍 PagingAndSortingRepository 提供的方法:

// 返回所有的实体,根据Sort参数提供的规则排序。
Iterable<T> findAll(Sort sort);

// 返回一页实体,根据Pageable参数提供的规则进行过滤。
Page<T> findAll(Pageable pageable);

我们在看看JpaRepository 提供的方法:

// 将所有未决的更改刷新到数据库。
void flush();

// 保存一个实体并立即将更改刷新到数据库。
<S extends T> S saveAndFlush(S entity);

// 在一个批次中删除给定的实体集合,这意味着将产生一条单独的Query。
void deleteInBatch(Iterable<T> entities);

// 在一个批次中删除所有的实体。
void deleteAllInBatch();

// 根据给定的id标识符,返回对应实体的引用。
T getOne(ID id);

正是因为我们继承了JpaRepository接口,因此就拥有了上面的所有方法。他们是实现数据库表增删改查的功能。除此之外,Spring JPA还提供了一些自定义声明方法的规则。例如,在接口中使用关键字findBy,readBy,getBy作为方法名的前缀,然后拼接实体类中的属性字段变量(首字母大写),并可以选择拼接一些SQL查询关键字类组合成为一个查询方法。例如:findByUserNameLike(String name);就可以根据一个字符串名称模糊查询表记录了。这些方法同样只需要声明,不需要实现,Spring JPA就可以自动实现这些方法对应的功能。

接下来,我们修改 StudentController 控制器来注入并使用上面的 StudentInfoRepository 实体类

package com.demo.controller;

import com.demo.entity.StudentInfoEntity;
import com.demo.repository.StuentInfoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;
import java.util.Map;

@Controller
public class StudentController {

    @Autowired
    private StuentInfoRepository stuentInfoRepository;

    @RequestMapping("/student")
    public String student(Map<String, Object> map){

        List<StudentInfoEntity> list = stuentInfoRepository.findAll();
        map.put("list", list);
        return "student";
    }

}

接下来,我们创建 “resources\static\index.html” 和 “resources\templates\student.html” 视图文件

<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>index</title>
</head>
<body>

<a href="/student">student</a>

</body>
</html>
<!doctype html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>student</title>
</head>
<body>

<div th:each="item:${list}">
    <span th:text="${item.stuName}"></span>
</div>

</body>
</html>

这里我们使用 “thymeleaf” 模版来展示控制器传递过来的学生列表信息。

我们整体工程的结构如下

我们运行一下,查看结果

接下来,我们使用自定义SQL语句进行查询,使用@Query 注解自定义查询。

package com.demo.repository;

import com.demo.entity.StudentInfoEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

public interface StuentInfoRepository extends JpaRepository<StudentInfoEntity, Long> {

    @Query(value="select * from student_info where stu_id = :id", nativeQuery=true)
    StudentInfoEntity getStudentInfoById(int id);
    
}

以上需要解释的有两点,第一就是SQL语句里面的“:id”是一个占位符,它会对应方法里面的形参列表,如果有多个占位符的话,可以使用“@Param("id")”来绑定形参,如下所示:


package com.demo.repository;

import com.demo.entity.StudentInfoEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

public interface StuentInfoRepository extends JpaRepository<StudentInfoEntity, Long> {

    @Query(value="select * from student_info where stu_id = :id", nativeQuery=true)
    StudentInfoEntity getStudentInfoById(int id);

    @Query(value="select * from student_info where stu_id = :id and stu_name = :name", nativeQuery=true)
    StudentInfoEntity getStudentInfoByIdName(@Param("id") int id, @Param("name") String name);

}

第二解释的是“nativeQuery=true”,它代表本地SQL,是根据实际使用的数据库类型(比如MySQL)写的SQL。我们知道虽然SQL有自己的标准,但是各大数据库厂商在SQL语句上的实现还是有一些差距。JPA为了解决这个问题,它会根据自己的语法来制定SQL语句,这种SQL本身是不适用于任何数据库的,需要JPA将这种SQL转换成真正当前数据库所需要的SQL语法格式。这样做的好处在于,当我们从“MySQL”数据库迁移到“Oracle”数据库的时候,我们的SQL语句不用做任何的改动。当然,这需要我们去熟悉JPA语法规范的SQL。对于大部分程序开发人员来说,最简单粗暴的方式还是使用“nativeQuery=true”来标注为本地SQL语句,保证我们写的SQL语句在一种数据库(比如MySQL)上正确运行就可以啦。

接下来,我们在 StudentController 中完成调用

    @RequestMapping("/info")
    public String info(Integer id, String name, Map<String, Object> map){

        StudentInfoEntity info = stuentInfoRepository.getStudentInfoByIdName(id, name);
        map.put("info", info);
        return "student";
    }

接下来继续补全 “index.html” 和 "student.html" 中内容

<a href="/student">student</a>
<br />
<a href="/info?id=1&name=小明">info?id=1&name=小明</a>
<div th:if ="${info}">
    <span th:text="${info.stuId}"></span>
    <span th:text="${info.stuName}"></span>
</div>

接下来,我们重新运行测试一下

当我们的SQL语句是一个insert,update,delete类型的语句是,需要配合@Modifying注解

@Modifying
@Transactional
@Query(value="update student_info set stu_name = :name where stu_id = :id", nativeQuery=true)
void updateStudentInfo(@Param("id") int id, @Param("name") String name);

@Transactional是开启事务,配合@Modifying一起使用。

这事务注解是:javax.transaction.Transactional; 不要引入错了。

接下来,我们在 StudentController 中完成调用

    @RequestMapping("/edit")
    public String edit(Integer id, String name, Map<String, Object> map){

        stuentInfoRepository.updateStudentInfo(id, name);
        map.put("info", null);
        return "student";
    }

接下来继续补全 “index.html” 和 "student.html" 中内容

<a href="/student">student</a>
<br />
<a href="/info?id=1&name=小明">info?id=1&name=小明</a>
<br />
<a href="/edit?id=1&name=张三">edit?id=1&name=张三</a>

由于我们向视图传递的是null对象,所以不用修改 "student.html" 了。

接下来,我们重新运行测试一下

我们去数据库里面核实一下

最后在说一个返回结果的问题,一般情况下,我们都会为查询结果定义一个实体类。但是,对于一些连表查询的话,因为涉及返回的结果字段不明确,因此如果为此定义一个实体类实在不是很划算,我们可以借助Map来实现。如下所示:

    @Query(value = "SELECT s.stu_id, s.stu_name, s.class_id, c.class_name FROM student_info AS s JOIN class_info AS c ON s.class_id = c.class_id WHERE s.stu_id = :id", nativeQuery=true)
    Map<String, Object> getStudentClassInfo(int id);

在上述查询SQL中,我们使用“student_info”表作为主表,然后关联查询“class_info”表中的班级名称“class_name”字段。接下来,我们在 StudentController 中完成调用

    @RequestMapping("/joinTest")
    public String joinTest(Integer id, Map<String, Object> map){

        Map data = stuentInfoRepository.getStudentClassInfo(id);
        map.put("data", data);
        return "student";
    }

接下来继续补全 “index.html” 和 "student.html" 中内容

<a href="/student">student</a>
<br />
<a href="/info?id=1&name=小明">info?id=1&name=小明</a>
<br />
<a href="/edit?id=1&name=张三">edit?id=1&name=张三</a>
<br />
<a href="/joinTest?id=1">joinTest?id=1</a>
<div th:if ="${data}">
    <span th:text="${data.stu_id}"></span>
    <span th:text="${data.stu_name}"></span>
    <span th:text="${data.class_name}"></span>
</div>

接下来,我们重新运行测试一下

完整 “SpringBootJpaDemo” 工程文件下载: https://download.youkuaiyun.com/download/richieandndsc/89900409

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值