错误前:
@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); 问题解决!!!