錯誤前:
@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);
問題解決!!!
