Java 8 Spring Data JPA Parameter binding

2019-02-21 12:18发布

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

from Address a where a.addressType = :addressType

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

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.

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

2条回答
Deceive 欺骗
2楼-- · 2019-02-21 12:55

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.

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

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

查看更多
叛逆
3楼-- · 2019-02-21 13:02

The answer given by @JB Nizet is correct, but I just wanted to point out the way to add the -parameters flag for the Java 8 compiler when using Eclipse. This is in Window -> Preferences:

enter image description here

Maven also allows adding the flags in the pom itself:

<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>
查看更多
登录 后发表回答