Java 8 Spring Data JPA 参数绑定 [英] Java 8 Spring Data JPA Parameter binding

查看:36
本文介绍了Java 8 Spring Data JPA 参数绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的@Repository 接口中,我使用包含参数 (addressType) 的 JPQL @Query 创建了自定义查找方法.

In my @Repository interface I created custom find method with JPQL @Query that contains parameter (addressType).

from Address a where a.addressType = :addressType

在方法中我没有在参数上指定@Param("addressType").所以我得到了

In the method I did not specify @Param("addressType") on the parameter. So I am getting

java.lang.IllegalArgumentException:参数绑定的名称不能为空或空!对于命名参数,您需要在 Java 版本中使用 @Param 查询方法参数 <8.

java.lang.IllegalArgumentException: Name for parameter binding must not be null or empty! For named parameters you need to use @Param for query method parameters on Java versions < 8.

好的,这已经很清楚了,但我使用的是 Java 8.那么这里的 Java 8 有什么特别之处?

Okay, this is pretty much clear, but I am using Java 8. So what is special about Java 8 here?

推荐答案

在 Java 8 中,您可以使用反射来访问方法的参数名称.这使得 @Param 注释变得不必要,因为 Spring 可以从方法参数的名称中推断出 JPQL 参数的名称.

In Java 8, you can use reflection to access names of parameters of methods. This makes the @Param annotation unnecessary, since Spring can deduce the name of the JPQL parameter from the name of the method parameter.

但是您需要在编译器中使用 -parameters 标志才能获得该信息.

But you need to use the -parameters flag with the compiler to have that information available.

参见 http://docs.oracle.com/javase/tutorial/reflect/member/methodparameterreflection.html.

这篇关于Java 8 Spring Data JPA 参数绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆