在dao中自定义了一个查询语句,是查询一个数据表中的某一列的总和。自定义查询语句如下:
@Query(value = "SELECT Sum(account.money) FROM account")
double totalMoney();
报错现象:
java.lang.IllegalStateException: Failed to load ApplicationContext
...此处省略N句代码...
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'accountServiceImpl': Unsatisfied dependency expressed through field 'accountDao'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract double com.neo.repository.AccountDao.totalMoney()!
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'accountDao': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract double com.neo.repository.AccountDao.totalMoney()!
...
Caused by: java.lang.NullPointerException
......org.springframework.data.jpa.repository.query.SimpleJpaQuery.validateQuery(SimpleJpaQuery.java:87)
... 81 more
看看以上代码报了几个错:
IllegalStateException:非法语句错误,无法加载上下文。
从caused by中可以看出最主要的错误原因是:
Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Validation failed for query for method public abstract double com.neo.repository.AccountDao.totalMoney()!
意思就是说,调用AccountDao.totalMoney()错误。
为什么会产生这样的错误?
原来jpa中自定义的语句中没有加上
nativeQuery = true
那为什么没有加上nativeQuery = true
就会报错呢?
原来jpa执行自定义查询时from后面必须跟的是entity类名,例如这样:
@Query(value = "SELECT Sum(a.money) FROM Account a")
如上这样就不会报错了。
如果是from后面跟的是数据库中的表名,请加上:nativeQuery = true
,否则会报错。
至于为什么会这样,大概是:
JpaRepository<T, ID>
dao类继承Jpa时已经定义好了映射的实体类,如果不是相应实体类,那么会加载不上自定义的查询语句。