错误前:

@Service
String ids = "1,2,3,4,5";
this.UserDao.getUsers(ids);

@Repository
//报错
/*
org.springframework.dao.InvalidDataAccessApiUsageException: 
Parameter value [1,2,3,4] did not match expected type [java.lang.Integer (n/a)]; 
nested exception is java.lang.IllegalArgumentException: 
Parameter value [1,2,3,4] did not match expected type [java.lang.Integer (n/a)]
*/
@Query("SELECT s from User s WHERE s.id IN(:ids)")
List<User> getUsers(@Param("ids") String ids);

//强行执行自定义sql
@Query(nativeQuery = true, value = "SELECT * from User WHERE id IN(?1)")
List<User> getUsers(@Param("ids") String ids);

强行执行自定义sql之后,你会发现,结果和预期不一致
放到sqlyog里面执行自定义sql
SELECT * from User WHERE id IN(1,2,3,4,5);
发现结果没错。错在哪里吗?
放到sqlyog里面执行
SELECT * from User WHERE id IN(”1,2,3,4,5“);
结果和程序神奇的一致,只查询id=1的一条记录,问题就在这里,有引号!!!

  

修改后:

@Service
String ids = "1,2,3,4,5";
List<Integer> userIds = new ArrayList<>();
String[] userArray = ids.split(",");
for(String id : userArray){
    userIds.add(Integer.parseInt(id));
}
this.UserDao.getUsers(userIds);

@Repository
@Query("SELECT s from User s WHERE s.id IN(:ids)")
List<User> getUsers(@Param("ids") List<Integer> ids);

问题解决!!!

  

相关文章:

  • 2021-10-23
  • 2022-02-22
  • 2021-11-25
  • 2022-01-21
  • 2022-12-23
  • 2022-12-23
  • 2021-09-25
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-02
  • 2022-02-01
  • 2021-12-13
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案