MyBatis 개요
MyBatis는 JDBC를 기반으로 한 ORM 프레임워크로, 데이터베이스 연동을 간소화합니다. Apache iBatis에서 발전했으며 현재는 GitHub에서 관리됩니다.
환경 설정 및 의존성
핵심 JAR
- mybatis-3.5.6.jar: 핵심 기능 포함
필수 의존성
- asm-7.0.jar: 바이트코드 분석
- cglib-3.3.0.jar: 동적 프록시 구현
- slf4j-api-1.7.30.jar: 로깅 인터페이스
데이터베이스 드라이버
- mysql-connector-java-8.0.25.jar
- ojdbc8.jar
핵심 구성 파일
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<environments default="prod">
<environment id="prod">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${db.driver}"/>
<property name="url" value="${db.url}"/>
<property name="username" value="${db.user}"/>
<property name="password" value="${db.pass}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/example/EmployeeMapper.xml"/>
</mappers>
</configuration>
주요 요소 설명
- <transactionManager>: JDBC 또는 MANAGED 트랜잭션 관리
- <dataSource>: POOLED/UNPOOLED/JNDI 연결 방식 지정
- <mappers>: SQL 매핑 파일 경로 지정
- <properties>: 외부 설정 파일 로드
매퍼 파일 구조
<mapper namespace="com.example.EmployeeMapper">
<select id="findEmployee" resultType="Employee">
SELECT * FROM employees WHERE emp_id = #{id}
</select>
</mapper>
파라미터 처리
다중 파라미터 전달
<select id="findByCondition" resultType="Employee">
SELECT * FROM employees
WHERE emp_name = #{name} AND department = #{dept}
</select>
Map 활용
Map<String, Object> params = new HashMap<>();
params.put("name", "김사원");
params.put("dept", "개발팀");
Employee emp = mapper.findByMap(params);
기본 SQL 연산
데이터 삽입
<insert id="addEmployee">
INSERT INTO employees VALUES(#{id}, #{name}, #{position})
</insert>
데이터 삭제
<delete id="removeEmployee">
DELETE FROM employees WHERE emp_id = #{id}
</delete>
동적 SQL
조건별 필터링
<select id="searchEmployees" resultType="Employee">
SELECT * FROM employees
<where>
<if test="name != null">
AND emp_name LIKE #{name}
</if>
<if test="dept != null">
AND department = #{dept}
</if>
</where>
</select>
집합 처리
<select id="findInDepartments" resultType="Employee">
SELECT * FROM employees
WHERE dept_id IN
<foreach item="item" collection="list"
open="(" separator="," close=")">
#{item}
</foreach>
</select>
SQL 조각 재사용
<sql id="empColumns">
emp_id, emp_name, department
</sql>
<select id="getAll" resultType="Employee">
SELECT <include refid="empColumns"/>
FROM employees
</select>