목차.

  1. MyBatis 기본 설정
  2. CRUD 예제 만들기
  3. SQL mapper 파라메터 전달

MyBatis는 iBATIS의 새로운 버전으로 국내에서 가장 많이 사용되는 ORM Framework[각주:1] 중 하나이다. MyBatis는 문서화가 잘 되어 있다고 하지만 막상 실전에 적용시키기에는 이전 버전인 iBATIS에 비해 예제가 부족한 듯하여 자료 정리겸 레퍼런스를 만들어 볼까 한다.

우선 MyBatis를 설정하고 간단한 예제를 만들어 본 다음, Spring 3로 Bean을 등록하는 예제로 확장시켜 볼 예정이다.

본 예제는 다음과 같은 개발환경하에서 작성되었다.

  • Eclipse Java EE IDE (Juno)
    • PropertiesEditor (by Sou Miyazaki)
  • Java SE 6
  • MyBatis-3.1.1
  • JUnit 4

1. MySQL Table

CREATE TABLE user (
	id INT(5) NOT NULL PRIMARY KEY AUTO_INCREMENT,
	username VARCHAR(16) NOT NULL,
	password VARCHAR(16) NOT NULL,
	level INT(2) NOT NULL DEFAULT '0',
	reg_date DATE NOT NULL
);

2. Configuration

development.properties

url=jdbc:mysql://localhost/development?characterEncoding=utf-8
driver=com.mysql.jdbc.Driver
user=development
pass=test123

mysql-config.xml

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <configuration> <properties resource="exercise/mybatis3/persistence/development.properties"/> <settings> <setting name="defaultExecutorType" value="REUSE"/> <setting name="useGeneratedKeys" value="true"/> </settings> <typeAliases> <!-- Type Aliases List --> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC"/> <dataSource type="JNDI"> <property name="initial_context" value="java:comp/env" /> <property name="data_source" value="jdbc/insure"/> </dataSource> </environment> <environment id="testing"> <transactionManager type="MANAGED"> <property name="closeConnection" value="false"/> </transactionManager> <dataSource type="POOLED"> <property name="driver" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${user}" /> <property name="password" value="${pass}" /> </dataSource> </environment> </environments> <mappers> <!-- Mapper List --> </mappers> </configuration>

3. SQL Mapper (CRUD)

UserMapper.xml

<?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="exercise.mybatis3.persistence.UserMapper">
	<insert id="add" parameterType="User"
			useGeneratedKeys="true" keyProperty="id">
		INSERT INTO user (username, password, level, reg_date)
		VALUES (#{username}, #{password}, 1, NOW())
	</insert>
	
	<select id="count" resultType="int">
		SELECT COUNT(*) FROM user
	</select>
</mapper>

UserMapper.java

package exercise.mybatis3.persistence;

import exercise.mybatis3.domain.User;

public interface UserMapper {
	
	public void add(User user);
	
	public int count(); 
}

4. Domain Object

User.java

package exercise.mybatis3.domain;

import java.io.Serializable;

public class User implements Serializable {

	private static final long serialVersionUID = 1L;
	
	private Integer id;
	private String username;
	private String password;
	private Integer level;
	private String regDate;

	public User() {
		// TODO Auto-generated constructor stub
	}
	
	public User(String username, String password) {
		this.username = username;
		this.password = password;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public Integer getLevel() {
		return level;
	}

	public void setLevel(Integer level) {
		this.level = level;
	}

	public String getRegDate() {
		return regDate;
	}

	public void setRegDate(String regDate) {
		this.regDate = regDate;
	}

}

5. Unit Test (CRUD)

TestUserMapper.java

package exercise.mybatis3.test;

import static org.junit.Assert.assertThat;
import static org.hamcrest.CoreMatchers.is;

import java.io.Reader;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import exercise.mybatis3.domain.User;
import exercise.mybatis3.persistence.UserMapper;

public class TestUserMapper {
	static SqlSessionFactory sf;
	User user;

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		String resource = "exercise/mybatis3/persistence/mybatis-config.xml";
		Reader reader = Resources.getResourceAsReader(resource);
		sf = new SqlSessionFactoryBuilder().build(reader, "testing");
		
	}
	
	@Before
	public void setUp() {
		user = new User("user1", "1234");
	}

	@Test
	public void testAdd() {
		SqlSession session = sf.openSession();
		
		try {
			UserMapper mapper = session.getMapper(UserMapper.class);
			
			mapper.add(user);
			assertThat(1, is(mapper.count()));
		} finally {
			session.close();
		}
	}

}


  1. 데이터베이스와 객체와의 관계를 맵핑시켜 퍼시스턴스 로직처리를 도와주는 프레임워크 (Object Relational Mapping) [본문으로]

+ Recent posts