MyBatis를 사용할 때 가장 반복적이고 귀찮은 작업 중 하나는 테이블 구조에 맞게 Model, Mapper Interface, XML 파일을 일일이 작성해야 한다는 점입니다.
이때 MyBatis Generator(MBG)를 활용하면 DB 테이블로부터 필요한 Java 코드들을 자동으로 생성할 수 있어 생산성이 크게 향상됩니다.
이 글에서는 Spring Boot + Maven 프로젝트에서 MyBatis Generator를 자동으로 설정하고 사용하는 방법을 실무 기준으로 정리해봅니다.
사용 환경
- Java 17+
- Spring Boot 3.x
- Maven
- MyBatis or MyBatis-Spring-Boot-Starter
- MySQL or MariaDB
1. MyBatis Generator 의존성 추가
pom.xml
에 다음과 같은 plugin을 추가합니다:
<build>
<plugins>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.4.1</version>
<configuration>
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
<executions>
<execution>
<id>Generate MyBatis Artifacts</id>
<goals>
<goal>generate</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
2. generatorConfig.xml 생성
src/main/resources/generatorConfig.xml 파일을 생성하고, 다음과 같이 작성합니다:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="MySQLContext" targetRuntime="MyBatis3" defaultModelType="flat">
<!-- 주석 제거 -->
<commentGenerator>
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- DB 연결 정보 -->
<jdbcConnection
driverClass="com.mysql.cj.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/yourdb?serverTimezone=Asia/Seoul"
userId="youruser"
password="yourpass"/>
<!-- 생성될 모델 클래스 위치 -->
<javaModelGenerator targetPackage="com.example.model" targetProject="src/main/java"/>
<!-- Mapper XML 파일 위치 -->
<sqlMapGenerator targetPackage="mapper.xml" targetProject="src/main/resources"/>
<!-- Mapper 인터페이스 위치 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/>
<!-- 테이블 설정 -->
<table tableName="user" domainObjectName="User"/>
<table tableName="post" domainObjectName="Post"/>
</context>
</generatorConfiguration>
여러 테이블 추가 가능
domainObjectName은 Java 클래스 이름입니다.
3. 실행 방법 (Maven CLI 또는 IDE)
터미널에서 실행
./mvnw mybatis-generator:generate
또는
mvn mybatis-generator:generate
IntelliJ 실행
Maven → Plugins → mybatis-generator → generate 실행
4. 생성 결과 예시
public class User {
private Long id;
private String username;
...
}
public interface UserMapper {
int insert(User user);
User selectByPrimaryKey(Long id);
List<User> selectByExample(UserExample example);
}
<!-- resources/mapper/xml/UserMapper.xml -->
<mapper namespace="com.example.mapper.UserMapper">
<select id="selectByPrimaryKey" resultMap="BaseResultMap">
SELECT ... FROM user WHERE id = #{id}
</select>
</mapper>
실무 팁
DTO/Entity 패키지 분리
- model → 자동 생성용
- entity 또는 domain → 실제 사용용
MyBatis Generator는 mergeable="false"
로 설정하면 기존 XML 파일을 덮어쓰지 않음
<sqlMapGenerator targetPackage="mapper.generated" targetProject="src/main/resources" mergeable="false" />
Lombok 적용하고 싶다면 plugin 추가
<plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"/>
<plugin type="org.mybatis.generator.plugins.SerializablePlugin"/>
<plugin type="org.mybatis.generator.plugins.ToStringPlugin"/>
추천 디렉토리 구조
src/
├── main/
│ ├── java/
│ │ └── com/example/
│ │ ├── model/ ← 자동 생성 Model
│ │ ├── mapper/ ← 자동 생성 Mapper 인터페이스
│ │ └── domain/ ← 직접 사용하는 DTO 또는 Entity
│ └── resources/
│ └── mapper/
│ └── xml/ ← 자동 생성된 Mapper XML
마무리
MyBatis Generator는 단순히 SQL Mapper를 자동으로 만들어주는 도구 이상입니다.
코드 품질을 유지하면서 개발 속도를 빠르게 할 수 있는 핵심 도구죠.
초기 세팅은 다소 번거로울 수 있지만, 한 번 구성해두면 반복되는 작업을 줄이고
팀 전체 개발 생산성을 크게 끌어올릴 수 있습니다.
댓글