首页 > 解决方案 > java - 如何在Java存储库文件中的本机sql查询中传递参数?

问题描述

这是我的查询,我写在存储库文件中。

@Query(value = "select * from A a join B b ON a.allocateBy = b.empNo join D d ON b.departmentName = d.departmentName where a.allocateBy in (:allocateByList)",  nativeQuery = true)

ArrayList<A> findAllByAllocateByIn(@Param("allocateByList") String allocateByList);

没有错误,但 :allocateByList 没有获取数据。我之前已经打印了 allocateByList 的值。它有数据。

我错过了什么吗?

标签: javasqlhibernateormrepository

解决方案


正如您在评论中提到的那样,“allocateByList”具有例如值“'M06','M81'”。

因此,您正在执行以下请求:

select * 
from A a 
join B b ON a.allocateBy = b.empNo 
join D d ON b.departmentName = d.departmentName
where a.allocateBy in ('''M06'',''M81''')

您正在寻找在“'M06','M81'”处具有“allocateBy”值的值“a”。

我相信您想要一个具有“M06”值或“M81”值的值。

所以你必须做以下修改:

1)修改allocateByListfrom的类型StringList<String>

2)正确格式化搜索值:您必须拆分,然后删除'包装您的值。

所以:

String allocateByListInitial = "'M06','M81'";

String[] allocateByListSplitted = allocateByListInitial.split(",");

// allocateByListSplitted = ["'M06'", "'M81'"] (with single quote wrapping each value)

List<String> allocateByList = Arrays.stream(allocateByListSplitted)
                                    .map(str -> str.substring(1, str.length() - 1)) // Remove first and last character of the string
                                    .collect(Collectors.toList());

// allocateByList = ["M06", "M81"] (without the single quote)

List<PointAllocation> pointAllocations = myRepo.findAllByAllocateByIn(allocateByList);

推荐阅读