7.5 JPA支持

第 52 节 / 共 81 节 课程:前后端穿透

JPA(Java Persistence API)技术用于在关系数据库中管理Java对象的持久化,它允许我们将数据库表映射为Java类。在Spring Boot中,使用JPA可以大大简化数据库操作,Spring Boot适用的JPA实现是Hibernate。本节将介绍如何在Spring Boot应用中使用JPA。

首先,在pom.xml文件中引入必要的依赖来支持JPA和H2数据库,如代码7-10所示:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>

在pom.xml中添加配置

这段代码插入到如图7-13所示的位置:

在pom.xml添加配置
在pom.xml添加配置

这里com.h2database是一个轻便的内存数据库,它在运行时被Spring Boot自动配置,使我们免于手动配置数据库,快速了解JPA的特性。

此段配置保存到pom.xml文件后,项目马上就会进行编译并下载相应的资源。

让我们深入看看几个关键的Java文件。类和包的创建步骤略过,可自行操作。

1.Customer.java

这是一个实体类,与数据库表直接映射。使用@Entity标签表明其作为持久化对象,并且每个属性与数据库列对应。示例代码如代码7-11所示:

package com.example.accessingdatajpa;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer{
     //@Id表示id这个属性是主键
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;
    private String firstName;
    private String lastName;
    protected Customer(){
    }
    public Customer(String firstName,String lastName){
        this.firstName=firstName;
        this.lastName=lastName;
    }
    @Override
    public String toString(){
        return String
            .format("Customer[id=%d, firstName='%s', lastName='%s']",id,firstName,lastName);
    }
    public Long getId(){
        return id;
    }
    public String getFirstName(){
        return firstName;
    }
    public String getLastName(){
        return lastName;
    }
}

实体类Customer.java

2.CustomerRepository.java

这个类表示数据持久层的接口,它继承CrudRepository提供基本的CRUD操作。我们定义一些自定义查询方法来满足业务需求,如代码7-12所示:

package com.example.accessingdatajpa;
import java.util.List;
import java.util.Optional;
 
import org.springframework.data.repository.CrudRepository;
 
public interface CustomerRepository extends CrudRepository<Customer,Long>{
List<Customer> findByLastName(String lastName);
Optional<Customer> findById(Long id);
}

数据库访问层类 CustomerRepository.java

这是一个接口,它需要继承一个接口CrudRepository,这个接口需要将指定泛型的类型,第一个参数是要处理的映射类,第二个参数是个Long类型,它是这个映射类的主键的类型。

这里定义了两个方法,findByLastName通过lastName查找Customer,结果是一个集合;findById通过主键id查找,结果唯一。

这个接口是用来定义处理Customer表的所有方法的,此处只列了两个,假如还有更多对于Customer表的操作(例如更新、删除),对应的方法也要写在此类。

看到这里,可能已经有人发现:CustomerRepository只是一个接口,并没有实现,实现类在哪里?具体要执行的SQL语句在哪里?

不需要实现类。实现由Spring Data JPA提供,你只需要定义接口,具体SQL语句是自动生成的。在程序运行时,Spring框架会自动为CustomerRepository创建一个实现类,并且此实现类会作为一个Spring Bean被注入到你的服务(Service)层或其他需要依赖注入的组件,供应用程序使用。

另外findById和findByLastName并不是随便写的,必须在Customer类里存在id和lastName这两个属性。findBy也是规范之一。

关于GRUD操作方法的规范命名,Spring Boot的JPA提供了很完备的命名规范,关于repository的更多细节将在7.8节介绍。

3.修改启动类

在启动类添加方法CommandLineRunner,此方法来演示如何操作数据库。Spring Boot应用在启动时会运行这个方法提供的代码,它合理地使用了JPA仓库来保存和检索Customer实例。现在的启动类DemoApplication 的代码如7-13所示:

package com;
 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
import com.example.accessingdatajpa.Customer;
import com.example.accessingdatajpa.CustomerRepository;
 
@SpringBootApplication
@RestController
public class DemoApplication {
 
private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);
 
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
 
@GetMapping("/hello")
public String hello(@RequestParam(value = "name", defaultValue = "World") String name) {
return String.format("Hello %s!", name);
}
 
@Bean
public CommandLineRunner demo(CustomerRepository repository)
 {
return (args) -> {
// 保存一些Customer对象
repository.save(new Customer("Jack", "Bauer"));
repository.save(new Customer("Chloe", "O'Brian"));
repository.save(new Customer("Kim", "Bauer"));
repository.save(new Customer("David", "Palmer"));
repository.save(new Customer("Michelle", "Dessler"));
// 从数据库取得所有Customer对象
log.info("Customers found with findAll():");
log.info("-------------------------------");
for (Customer customer : repository.findAll()) {
log.info(customer.toString());
}
log.info("");
// 通过id取得一个Customer对象
Customer customer = repository.findById(1L).get();
log.info("Customer found with findById(1L):");
log.info("--------------------------------");
log.info(customer.toString());
log.info("");
// 通过lastName取得Customer对象
log.info("Customer found with findByLastName('Bauer'):");
log.info("---------------------------------");
repository.findByLastName("Bauer").forEach(bauer -> {
log.info(bauer.toString());
 
});
log.info("");
};
}
}

在启动类添加测试方法

含有@bean标签的方法,都会在启动的时候初始化,这个方法展示了Customer的两个获取方法。重新启动Spring Boot,运行的结果直接显示在控制台,如图7-14所示:

测试结果
测试结果

《前后端穿透》课程目录

按教材顺序从 Vue 前端讲到 Spring Boot 后端:模板、组件、路由、axios、Controller、JPA、文件上传、Nginx 部署,最后完成学习平台实训。10 章 71 节,配 220 张操作截图与可直接运行的代码。