일정한 비율로 리스트 분할하기
When
서버 개발중 아이템리스트를 DB일괄 저장을 할 때 다음과 같은 에러를 만나게 된다.
파라미터의 크기가 범위를 벗어나서 예외가 발생하게 되는데 DB설정으로 인한 방법을 생각할 수 있으나
접근권한이 없을때는 리스트를 분할해서 호출하는 방법을 생각할 수 있다.
### Cause: com.microsoft.sqlserver.jdbc.SQLServerException: The incoming request has too many parameters.
The server supports a maximum of 2100 parameters. Reduce the number of parameters and resend the request.
; uncategorized SQLException for SQL []; SQL state [S0001]; error code [8003]; The incoming request has too many parameters.
How
이 경우 해결방법은 라이브러리를 활용한 아래와 같다.
Apache Commons
리스트와 분할할 값을 입력하면 리스트의 리스트가 생성된다.
ListUtils.partition(list, 분할할 값)
public void insertItems(List<Item> items) {
for (List<Item> partitionItems : ListUtils.partition(items, 50)) {
sqlSessionTemplate.getMapper(ItemMapper.class).insertItems(partitionItems);
}
}
Guava
위와 동일하게 나눌 값을 입력하면 리스트의 리스트가 생성된다.
Lists.partition(list, 분할할 값)
public void insertItems(List<Item> items) {
for (List<Item> partitionItems : Lists.partition(items, 50)) {
sqlSessionTemplate.getMapper(ItemMapper.class).insertItems(partitionItems);
}
}