DynamicSQL을 이용하면 조건에 따라 다양한 쿼리를 데이터베이스에 전송할 수 있다. 새로운 조건이 추가되더라도 sql문을 일일이 만들지 않아도 되므로 코드의 양이 줄어들고 유지보수가 편해진다.
board-mapping.xml
WHERE 1=1 : AND 조건절을 붙이기 위해 무조건 참인 조건을 준 것이다.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="BoardDAO">
<resultMap id="boardResult" type="board">
<id property="seq" column="SEQ"/>
<result property="title" column="TITLE"/>
<result property="writer" column="WRITER"/>
<result property="content" column="CONTENT"/>
<result property="regDate" column="REGDATE"/>
<result property="cnt" column="CNT"/>
</resultMap>
<insert id="insertBoard">
<![CDATA[
INSERT INTO BOARD(SEQ, TITLE, WRITER, CONTENT)
VALUES((SELECT NVL(MAX(SEQ), 0) + 1 FROM BOARD),
#{title},#{writer},#{content})
]]>
</insert>
<update id="updateBoard">
<![CDATA[
UPDATE BOARD SET TITLE=#{title}, CONTENT=#{content}
WHERE SEQ=#{seq}
]]>
</update>
<delete id="deleteBoard">
<![CDATA[
DELETE BOARD WHERE SEQ=#{seq}
]]>
</delete>
<select id="getBoard" resultType="board">
<![CDATA[
SELECT * FROM BOARD WHERE SEQ=#{seq}
]]>
</select>
<select id="getBoardList" resultMap="boardResult">
SELECT * FROM BOARD
WHERE 1=1
<if test="searchCondition == 'TITLE'">
AND TITLE LIKE '%'||#{searchKeyword}||'%'
</if>
<if test="searchCondition == 'CONTENT'">
AND CONTENT LIKE '%'||#{searchKeyword}||'%'
</if>
ORDER BY SEQ DESC;
</select>
</mapper>