728x90
MyBatis는 iBATIS의 새로운 버전으로 국내에서 가장 많이 사용되는 ORM Framework 중 하나이다. MyBatis는 문서화가 잘 되어 있다고 하지만 막상 실전에 적용시키기에는 이전 버전인 iBATIS에 비해 예제가 부족한 듯하여 자료 정리겸 레퍼런스를 만들어 볼까 한다. 1
우선 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
1 2 3 4 5 6 7 | 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
1 2 3 4 | url=jdbc:mysql: //localhost/development ?characterEncoding=utf-8 driver=com.mysql.jdbc.Driver user=development pass=test123 |
mysql-config.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 | < p ><? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" < 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 ></ p > |
3. SQL Mapper (CRUD)
UserMapper.xml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <? xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" < 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
1 2 3 4 5 6 7 8 9 10 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 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(); } } } |
출처: http://jeongsam.net/259
'프로그래밍 > ibatis' 카테고리의 다른 글
[MyBatis] $ 과 # 차이점 (0) | 2014.11.18 |
---|---|
iBatis 복수 parameter넘기는법 (0) | 2014.11.18 |
[스크랩]resultMap, resultClass, parameterClass (0) | 2014.10.14 |