我正在将 Hibernate JPA 与 Spring Boot 结合使用,但从 CRUDRepository
返回结果时遇到问题,我在其中使用 @Query
编写了自定义 SQL 查询标签。当我访问 DAO 并执行该方法时,它正常触发,但查询没有返回任何内容。
public interface ContactRepository extends CrudRepository<Contact, BigInteger> {
@Query(value ="SELECT * FROM all_contacts ac WHERE ac.userid= :userId " +
"AND LOWER(ac.city) LIKE CONCAT('%', LOWER(:city), '%')",
nativeQuery=true)
List<Contact> findAllUserContactsByCityPartialMatch(@Param("city") String city, @Param("userId") BigInteger userId);
}
当我在某个地方的模型或 Controller 中触发代码时:
@Autowired
ContactRepository contactDAO
List<Contact> results = contactDAO.findAllUserContactsByCityPartialMatch("Chicago", 12345);
结果
将始终为空
我的记录器告诉我它正在触发此查询:
SELECT * FROM all_contacts ac
WHERE ac.userid= ? AND LOWER(ac.city) LIKE CONCAT('%', LOWER(?), '%')
我知道查询没问题,因为当我运行查询并在 MySQL 终端中手动填写字段时,我得到了结果。
SELECT * FROM all_contacts ac
WHERE ac.userid= 12345 AND LOWER(ac.city) LIKE CONCAT('%', LOWER("Chicago"), '%')`
另外,我知道数据库配置正确,因为如果我运行说
Iterable<Contact> contactItr = contactDAO.findAll();
在前面提到的同一模型中,我从数据库返回了几个持久化结果。
我的想法是,它没有填充参数或使用 CRUDRepository
类中的参数执行它们,但我不确定。有什么想法吗?谢谢!
最佳答案
JPA 中的 native 查询不支持命名参数。您可以使用位置参数。
您也可以使用 JPA 查询语言,而无需 @Query
,例如:
public interface ContactRepository extends CrudRepository<Contact, BigInteger> {
List<Contact> findAllByCityContainingIgnoreCaseAndUserId(String city, BigInteger userId);
}
关于java - @Query注解不填充和执行参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46676155/