Spring JPA 拓展
本节记录了一组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支持
例45:使Spring数据支持web
@Configuration
@EnableWebMvc
@EnableSpringDataWebSupport
class WebConfiguration {}
@EnableSpringDataWebSupport
注释注册了一些我们稍后将讨论的组件。它还将检测类路径上的Spring HATEOAS,并为其注册集成组件(如果存在的话)。
或者,如果您使用XML配置,将SpringDataWebConfiguration
或HateoasAwareSpringDataWebConfiguration
注册为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
的配置注册了几个基本组件:
DomainClassConverter
让Spring 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()
来访问该实例,可以解析该实例。
用于可分页和排序的HandlerMethodArgumentResolvers
上一节中显示的配置片段还注册了一个PageableHandlerMethodArgumentResolver
以及SortHandlerMethodArgumentResolver
的实例。注册使Pageable
和Sort
成为有效的控制器方法参数,如下面的示例所示:
例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
尝试使用以下默认配置从请求参数派生一个可分页实例:
要自定义这个行为,需要注册一个实现PageableHandlerMethodArgumentResolverCustomizer
接口或SortHandlerMethodArgumentResolverCustomizer
接口的bean。它的customize()
方法将被调用,从而允许您更改设置,如下面的示例所示:
@Bean SortHandlerMethodArgumentResolverCustomizer sortCustomizer() {
return s -> s.setPropertyDelimiter("<-->");
}