본문 바로가기
공부/Trouble Shooting

DB 접근 속도 향상 (addBatch 메서드 , autoCommit : false)

by son_i 2023. 9. 10.
728x90
addBatch는 쿼리 실행을 하지 않고 쿼리 구문을 메모리에 올려두었다가, 실행 명령(executeBatch)이 있으면 한번에 DB쪽으로 쿼리를 날림.

다중 처리(Array Processing) 기능을 활용하면 한 번의 SQL 수행으로 대량의 로우를 동시에 insert/update/delete 할 수 있다.

※ DB의 commit 설정이 autoCommit 인 경우, 배치에 상관없이 insert 가 되면 자동으로 커밋 되어 큰 차이가 나지 않음 -> 커넥션 설정 중 autoCommit 을 false 로 지정

db에 거리를 계산해서 업데이트할 때 2만개의 데이터라 시간이 오래걸렸는데

질의응답에 이런 질문에 대한 해답이 있었다.

<DistUpdateDAO>

			connection.setAutoCommit(false);

autoCommit을 false로 해주고

 

while (rs.next()) {
				double x_value = rs.getDouble("x");
				double y_value = rs.getDouble("y");

				double dist = distance(x, y, x_value, y_value);
				dist = Math.round(dist * 10000) / 10000.0;
				String updatesql = "update wifi_list set dist= ?";
				preparedStatement = connection.prepareStatement(updatesql);
				preparedStatement.setDouble(1, dist);
				
				preparedStatement.addBatch();
			}
			preparedStatement.executeBatch();
			preparedStatement.clearBatch();

addBatch로 쿼리문을 메모리에 올려주고

다 끝나면 실행명령을 executeBatch로 시켜서 한 번에 쿼리를 날린다.

 

훨씬 빨라졌다 !! 


완전 실수를 해버렸다

String updatesql = "update wifi_list set dist= ?";
			preparedStatement = connection.prepareStatement(updatesql);
			int i = 0;
			while (rs.next()) {
				
				double x_value = rs.getDouble("x");
				double y_value = rs.getDouble("y");
				System.out.println(i++);
				double dist = distance(x, y, x_value, y_value);
				dist = Math.round(dist * 10000) / 10000.0;
				preparedStatement.setDouble(1, dist);
				
				preparedStatement.addBatch();
			}
			preparedStatement.executeBatch();
			preparedStatement.clearBatch();
			
			connection.commit();

저 쿼리문하고 preparedStatement를 밖에다 뺴줘야함 !

기존대로 하면 모든거리값에 똑같은 값이 들어간다. 아마도 마지막 요소랑 계산 값 ?

아니 왜 자꾸 똑같은 값이 다 들어가는 거지 ??????????

 

왜 ?????????????????????????????

결과값들은 다 잘 계산돼서 나오는데 대체 y..........

 

원인을 알아냈다 

String updatesql = "update wifi_list set dist= ? where manage_no=?";

여기에 where 조건을 안 넣어줘서 모두 같은 값으로 업데이트 된 거였음 ㅠㅠ 후우 찾아서 다행이다