Maven을 활용한 MyBatis 코드 자동 생성

MyBatis는 반자동 ORM 프레임워크로 분류됩니다. 따라서 개발자는 Mapping 파일을 직접 작성해야 하는 경우가 많은데, 이 작업은 실수하기 쉽습니다. mybatis-generator 플러그인을 사용하면 MyBatis에서 필요로 하는 DAO, Bean, Mapper XML 파일을 자동으로 생성할 수 있습니다.

본 글에서는 Eclipse IDE를 기준으로 설명하겠습니다.

  1. 데이터베이스 테이블 생성
CREATE TABLE `member` (
  `idx` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`idx`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
  1. Maven 프로젝트 생성

Eclipse에서 Maven Project를 생성합니다. "Create a simple project" 옵션을 선택하고 완료합니다.

  1. pom.xml에 의존성 추가
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.example</groupId>
  <artifactId>mybatis-auto-generator</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <name>mybatis-auto-generator</name>
  
  <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.5</version>
        </dependency>
    </dependencies>
    <build>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                    <version>3.8.0</version>
                </plugin>
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.5</version>
                    <dependencies>
                        <dependency>
                            <groupId>mysql</groupId>
                            <artifactId>mysql-connector-java</artifactId>
                            <version>5.1.38</version>
                        </dependency>
                    </dependencies>
                    <configuration>
                         <configurationFile>${basedir}/src/main/resources/generatorConfig.xml</configurationFile> 
                        <overwrite>true</overwrite>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>
  1. generatorConfig.xml 설정 파일 생성

src/main/resources 디렉토리에 generatorConfig.xml 파일을 생성합니다.

<?xml version="1.0" encoding="UTF-8"?>

<generatorConfiguration>
    <context id="dev" targetRuntime="MyBatis3">
        <plugin type="org.mybatis.generator.plugins.EqualsHashCodePlugin"></plugin>  
        <plugin type="org.mybatis.generator.plugins.SerializablePlugin"></plugin> 
        <plugin type="org.mybatis.generator.plugins.ToStringPlugin"></plugin> 
        <commentGenerator>
            <property name="suppressDate" value="true" />
            <property name="suppressAllComments" value="false" />
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost/testdb" userId="root" password="admin">
        </jdbcConnection>
        <javaTypeResolver>
            <property name="forceBigDecimals" value="false" />
        </javaTypeResolver>
        <javaModelGenerator targetPackage="com.example.entity"
            targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
            <property name="trimStrings" value="true" />
        </javaModelGenerator>
        <sqlMapGenerator targetPackage="com.example.mapper"
            targetProject="src/main/resources">
            <property name="enableSubPackages" value="true" />
        </sqlMapGenerator>
        <javaClientGenerator type="XMLMAPPER"
            targetPackage="com.example.repository" implementationPackage="com.example.repository.impl" targetProject="src/main/java">
            <property name="enableSubPackages" value="true" />
        </javaClientGenerator>
        
        
    </context>
</generatorConfiguration>

설정 파일의 주요 요소는 다음과 같습니다:

  • context: 생성 환경 설정
  • commentGenerator: 자동 생성 주석 설정 (suppressDate를 true로 설정하여 날짜 생성 방지)
  • jdbcConnection: 데이터베이스 연결 정보
  • javaModelGenerator: 엔티티 클래스 생성 위치 설정
  • sqlMapGenerator: Mapper XML 파일 생성 위치 설정
  • javaClientGenerator: DAO 인터페이스 생성 위치 설정
  • table: 생성 대상 테이블 지정
  1. Maven 의존성 다운로드

프로젝트를 우클릭하여 Maven > Update Project를 실행합니다. 의존성이 다운로드될 때까지 기다립니다.

  1. 코드 생성 실행

명령어 입력 후 빌드가 성공적으로 완료되면 파일이 생성됩니다.

  1. 결과 확인

프로젝트를 새로고침(F5)하면 생성된 파일을 확인할 수 있습니다.

target 디렉토리에 필요한 파일들이 자동으로 생성됩니다:

태그: MyBatis java maven ORM code-generation

6월 16일 23:28에 게시됨