在我的@Repository接口中,我使用包含参数(addressType)的JPQL @Query创建了自定义查找方法。
from Address a where a.addressType = :addressType
在方法中,我没有在参数上指定@Param(" addressType")。所以我得到了
java.lang.IllegalArgumentException:参数绑定的名称不能为null或为空!对于命名参数,您需要在Java版本上使用@Param作为查询方法参数< 8。
好的,这很清楚,但我使用的是Java 8.那么Java 8的特殊之处在哪里呢?
答案 0 :(得分:11)
在Java 8中,您可以使用反射来访问方法参数的名称。这使得@Param
注释变得不必要,因为Spring可以从方法参数的名称中推断出JPQL参数的名称。
但是你需要在编译器中使用-parameters
标志来获取该信息。
见http://docs.oracle.com/javase/tutorial/reflect/member/methodparameterreflection.html。
答案 1 :(得分:9)
@JB Nizet给出的答案是正确的,但我只是想指出在使用Eclipse时为Java 8编译器添加-parameters
标志的方法。这是在窗口 - >首选项:
Maven还允许在pom中添加标志:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<compilerArgs>
<arg>-verbose</arg>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
答案 2 :(得分:0)
JB Nizet和Xtreme Biker的答案都是正确的。我只想补充一下,如果您使用Spring Boot,spring-boot-starter-parent
(Gradle或Maven)已经为您添加了-parameters
编译器标志:
plugin {
delegate.groupId('org.apache.maven.plugins')
delegate.artifactId('maven-compiler-plugin')
configuration {
delegate.parameters('true')
}
}