자주 쓰는 Mybatis 정리 / MariaDB bulk insert, update 방법

Select 방법

Mybatis select 예시

<select id="get쿼리명" parameterType="java.util.HashMap" resultType="java.util.HashMap">
	SELECT
		a.컬럼명1
		<if test="파라미터1 != null and 파라미터1 != ''">
		, (SELECT 컬럼명 FROM 테이블명2 WHERE id = #{파라미터1}) AS 컬럼명2
		</if>
	FROM
		테이블명 a
	WHERE
	<choose>
		<when test="파라미터2 != null and 파라미터2 != ''">
			a.Key컬럼 = #{파라미터2}
		</when>
		<otherwise>
			a.Key컬럼 IS NULL
		</otherwise>
	</choose>
	AND a.delete_yn = 'N'
	ORDER BY sort
</select>

Mybatis 문법을 사용하면 파라미터의 존재 여부, 값에 따라 SQL 쿼리를 동적으로 변경할 수 있습니다.

Mybatis select count 예시

<select id="getCntByKey" parameterType="java.lang.Integer" resultType="java.lang.Integer">
	SELECT
		COUNT(*) AS cnt
	FROM
		테이블명
	WHERE
	<choose>
		<when test="파라미터 != null and 파라미터 != 0">
			Key컬럼 = #{파라미터}
		</when>
		<otherwise>
			Key컬럼 IS NULL
		</otherwise>
	</choose>
	AND delete_yn = 'N'
</select>

resultType을 int로 설정하면 null일 경우 BindingException이 발생할 수 있습니다.
int 대신 Integer를 사용하면 결과가 null이어도 반환 가능합니다.


Insert 방법

Mybatis insert 예시

<insert id="insertTest" parameterType="java.util.HashMap" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO 테이블명 (
        컬럼명1,
        컬럼명2
    ) VALUES (
         #{param1},
         #{param2}
     )
</insert>

useGeneratedKeys=”true” keyProperty=”id”하면 insert 한 row의 id 컬럼 값을 param Map에 담아 리턴합니다.

Mapper 예시

// 성공 여부를 받아야 하는 경우 int로 리턴
int insertTest(Map<String,Object> map) throws Exception;

Service 예시

// 쿼리 실행 후 성공 여부 Return
int insertResult = mapper.insertTest(paramMap);

if (insertResult > 0) {
	// 성공 처리
}else {
	// 에러 처리
}

// Insert ID 키 값
paramMap.get("id");

Bulk Insert 방법

Mybatis bulk insert 예시

<insert id="insert쿼리명" parameterType="java.util.HashMap" useGeneratedKeys="true" keyProperty="id">
	INSERT INTO 테이블명 (
		컬럼명1,
		컬럼명2
	) VALUES
	<foreach collection="list" item="item" separator=",">
	(
		#{item.파라미터1},
		#{item.파라미터2}
	)
	</foreach>
</insert>

파라미터로 받은 list를 반복하여 ,로 구분한 다중 insert 쿼리를 생성합니다.

Mapper 예시

Integer insert쿼리명(List<Map<String, Object>> paramList);

Bulk Update 방법

Mybatis bulk update 예시

<update id="update쿼리명" parameterType="java.util.HashMap">
    <foreach collection="list" item="item" separator=";">
    UPDATE
        테이블명
    SET
        컬럼명1 = #{item.파라미터1},
        컬럼명2 = #{item.파라미터2}
    WHERE
        조건컬럼명 = #{item.파라미터3}
    </foreach>
</update>

파라미터로 받은 list를 반복하여 ;로 구분한 다중 update 쿼리를 생성합니다.

Mapper 예시

Integer update쿼리명(List<Map<String, Object>> paramList);

application.properties 설정

spring.datasource.url=jdbc:log4jdbc:mariadb://DB서버명.ck39dp9w2h39.ap-northeast-2.rds.amazonaws.com:3306/DB명?allowMultiQueries=true

위와 같이, DB 연결 시 allowMultiQueries=true 옵션을 추가하지 않으면 ;로 구분한 다중 쿼리 실행이 불가합니다.

allowMultiQueries=true 아닌 경우 에러메세지

java.sql.SQLSyntaxErrorException: (conn=139024) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'UPDATE

Leave a comment