Spring JPA 拓展

时间:2022-07-24
本文章向大家介绍Spring JPA 拓展,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Spring JPA 拓展

翻译:Spring Data Extensions

本节记录了一组Spring数据扩展,它们支持在各种上下文中使用Spring数据。目前,大部分集成都是针对Spring MVC的。

1、Querydsl 拓展

Querydsl是一个框架,它支持通过其连贯的的API构造静态类型的sql类查询。

有几个Spring数据模块通过QuerydslPredicateExecutor提供与Querydsl的集成,如下面的示例所示:

例43:QuerydslPredicateExecutor接口

public interface QuerydslPredicateExecutor<T> {

  Optional<T> findById(Predicate predicate);  //查找并返回与谓词匹配的单个实体。

  Iterable<T> findAll(Predicate predicate);   //查找并返回与谓词匹配的所有实体。

  long count(Predicate predicate);            //返回与谓词匹配的实体数量。

  boolean exists(Predicate predicate);        //返回与谓词匹配的实体是否存在。

  // … more functionality omitted.
}

谓词的用法

要利用Querydsl支持,请在您的存储库接口上扩展QuerydslPredicateExecutor,如下面的示例所示:

例44:在存储库中整合Querydsl

interface UserRepository extends CrudRepository<User, Long>, QuerydslPredicateExecutor<User> {
}

前面的示例允许您使用Querydsl谓词实例编写类型安全的查询,如下面的示例所示:

Predicate predicate = user.firstname.equalsIgnoreCase("dave")
	.and(user.lastname.startsWithIgnoreCase("mathews"));

userRepository.findAll(predicate);

2、Web支持

本节包含Spring Data web支持的文档,因为它是在Spring Data Commons的当前(及以后)版本中实现的。由于新引入的支持改变了很多东西,所以我们在web.legacy中保留了以前的行为文档。

例45:使Spring数据支持web

@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
class WebConfiguration {}

@EnableSpringDataWebSupport注释注册了一些我们稍后将讨论的组件。它还将检测类路径上的Spring HATEOAS,并为其注册集成组件(如果存在的话)。

或者,如果您使用XML配置,将SpringDataWebConfigurationHateoasAwareSpringDataWebConfiguration注册为Spring bean,如下面的示例所示(例如SpringDataWebConfiguration)

例46:启用XML中的Spring Data web支持

<bean class="org.springframework.data.web.config.SpringDataWebConfiguration" />

<!-- If you use Spring HATEOAS, register this one *instead* of the former -->
<bean class="org.springframework.data.web.config.HateoasAwareSpringDataWebConfiguration" />

基础Web支持

上一节中展示@EnableSpringDataWebSupport的配置注册了几个基本组件:

  • DomainClassConverterSpring MVC从请求参数或路径变量中解析存储库管理的域类的实例。
  • HandlerMethodArgumentResolver实现,让Spring MVC从请求参数中解析可分页和排序实例。

DomainClassConverter允许您在Spring MVC控制器方法签名中直接使用域类型,因此您不需要通过存储库手动查找实例,如下面的示例所示:

例47:在方法签名中使用域类型的Spring MVC控制器

@Controller
@RequestMapping("/users")
class UserController {

  @RequestMapping("/{id}")
  String showUserForm(@PathVariable("id") User user, Model model) {

    model.addAttribute("user", user);
    return "userForm";
  }
}

如您所见,该方法直接接收用户实例,不需要进一步查找。通过让Spring MVC首先将path变量转换为域类的id类型,并最终通过调用为域类型注册的存储库实例的findById()来访问该实例,可以解析该实例。

目前,存储库必须实现CrudRepository才能被发现进行转换。

用于可分页和排序的HandlerMethodArgumentResolvers

​ 上一节中显示的配置片段还注册了一个PageableHandlerMethodArgumentResolver以及SortHandlerMethodArgumentResolver的实例。注册使PageableSort成为有效的控制器方法参数,如下面的示例所示:

例48:使用分页Pageable作为控制器参数

@Controller
@RequestMapping("/users")
class UserController {

  private final UserRepository repository;

  UserController(UserRepository repository) {
    this.repository = repository;
  }

  @RequestMapping
  String showUsers(Model model, Pageable pageable) {

    model.addAttribute("users", repository.findAll(pageable));
    return "users";
  }
}

前面的方法签名会导致Spring MVC尝试使用以下默认配置从请求参数派生一个可分页实例:

表1:Pageable 请求参数配置

参数名称

默认配置

page

您想要检索的页面,索引为0,默认值为0。

size

要检索的页面的大小,默认为20。

sort

排序属性,遵循property,property(,ASC|DESC)(,IgnoreCase)的格式,默认的排序是区分大小写的升序排序使用多个排序参数,如果你想切换方向或大小写敏感性,例如sort=firstname&sort=lastname,asc&sort=city,ignorecase。

​要自定义这个行为,需要注册一个实现PageableHandlerMethodArgumentResolverCustomizer接口或SortHandlerMethodArgumentResolverCustomizer接口的bean。它的customize()方法将被调用,从而允许您更改设置,如下面的示例所示:

@Bean SortHandlerMethodArgumentResolverCustomizer sortCustomizer() {
    return s -> s.setPropertyDelimiter("<-->");
}