我正在使用Spring-Data-Jpa创建我的存储库接口。在使用@query注释指定明确性查询时,我看到空指针异常。只有当我在查询中有多个命名参数时,才会发生这种情况,并且只有在使用命名参数的情况下才会发生。Spring-Data-Jpa - 使用多个命名参数时的空指针异常
public interface DeviceStatusRepository extends JpaRepository<DeviceStatus, Long>, JpaSpecificationExecutor<DeviceStatus> {
@Query(value = "SELECT ds from DeviceStatus ds where ds.deviceId like :deviceId and ds.chargingStatus like :chargingStatus")
Page<DeviceStatus> searchByMultipleFields(@Param("deviceId") String deviceId, @Param("chargingStatus") String chargingStatus, Pageable p);
}
下面是空指针异常:
Caused by: java.lang.NullPointerException
at org.springframework.data.jpa.repository.query.StringQuery.checkAndRegister(StringQuery.java:175)
at org.springframework.data.jpa.repository.query.StringQuery.parseLikeBindings(StringQuery.java:162)
at org.springframework.data.jpa.repository.query.StringQuery.<init>(StringQuery.java:68)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.<init>(SimpleJpaQuery.java:53)
at org.springframework.data.jpa.repository.query.SimpleJpaQuery.fromQueryAnnotation(SimpleJpaQuery.java:167)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:114)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:160)
at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:68)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:279)
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:147)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:153)
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:43)
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)
... 36 more
我也仰望春天,数据的StringQuery.java,甚至放在一个调试的角度来理解是什么导致了NPE。我注意到bindings
只有约deviceStatus
(我的查询中的第一个命名参数)条目,而它正在查找条目chargingStatus
(第二名param在我的查询中),它给了NPE在existing.hasPosition(binding.position)
作为position
是NULL(我猜的位置是对于命名参数预期为空)。看起来像一个错误,因为它没有正确处理null参数。
private final void checkAndRegister(LikeBinding binding) {
for (LikeBinding existing : bindings) {
if (existing.hasName(binding.name) || existing.hasPosition(binding.position)) {
Assert.isTrue(existing.equals(binding), String.format(MESSAGE, existing, binding));
}
}
this.bindings.add(binding);
}
Spring的数据版本,我现在用的就是1.4.0.M1
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.4.0.M1</version>
</dependency>
请注意,如果我使用了查询工作正常位置参数(?1,?2)代替命名参数(:deviceId,:chargingStatus)。
其他人看到这个问题吗?