1. maven 프로젝트로 전환 후에 defendencies에 MyBatis 내용 추가
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.7</version>
</dependency>
2. 프로젝트 안 src 에 log4j.properties, mybatisConfig.xml 파일 추가
MyBatis는 log4j가 반드시 있어야 함.
<log4j.properties>
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\zzz\\app.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
# Root logger option
log4j.rootLogger=DEBUG, file, stdout
# Log everything. Good for troubleshooting
log4j.logger.org.zerock.web=DEBUG
# Log all JDBC parameters
log4j.logger.org.hibernate.type=ALL
<mybatisConfig.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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@61.72.16.181:5024:orcl" />
<property name="username" value="user100" />
<property name="password" value="user100" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/ph/time/TimeMapper.xml"/>
<mapper class ="org.ph.member.MemberMapper"/>
<mapper class ="org.ph.bbs.BBSMapper"/>
</mappers>
</configuration>
*이 부분은 ctrl+space 키를 쓰기 위한 부분임.
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
*DB 주소와 ID, 비번 확인
3. Mapper 파일 만들기(java or xml)
Mybatis는 인터페이스로 된 Mapper 파일의 메소드에 어노테이션이 없으면 알아서 xml 파일을 탐색하는 듯.
package org.ph.member;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
public interface MemberMapper {
@Insert("insert into tbl_member (userid, userpw, username, phone, email)"
+ "values (#{userid}, #{userpw}, #{username}, #{phone}, #{email})")
public void create(MemberVO vo) throws Exception;
@Select("select * from tbl_member where userid = #{userid}")
public MemberVO read(String userid) throws Exception;
public void delete(String userid) throws Exception;
//어노테이션이 없으면 알아서 xml을 찾아감
}
4.GenericDAO 만들기
이는 각각 다른 VO 마다 DAO를 따로 만들어주는 것을 피하기 위한 것임.
package org.ph.dao;
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;
public class GenericDAO<VO, K> {
private static SqlSessionFactory sqlMapper;
static {
try {
Reader reader = Resources.getResourceAsReader("mybatisConfig.xml");
sqlMapper = new SqlSessionFactoryBuilder().build(reader);
} catch (Exception e) {
e.printStackTrace();
}
}
private String mapperName;
public GenericDAO(String mapperName) {
this.mapperName = mapperName;
}
public void create(VO vo) throws Exception {
try (SqlSession session = sqlMapper.openSession()) {
session.insert(mapperName + ".create", vo);
session.commit();
}
}
public VO read(K key) throws Exception {
try (SqlSession session = sqlMapper.openSession()) {
return session.selectOne(mapperName + ".read", key);
}
}
}
5. Junit 테스트 해보기
@Test
public void insertTest2(){
try(SqlSession session = sqlMapper.openSession()) {
GenericDAO<MemberVO, String> dao = new GenericDAO<MemberVO, String>("org.ph.member.MemberMapper");
MemberVO vo = new MemberVO();
vo.setUserid("leepan6");
vo.setUserpw("1234");
vo.setUsername("이이이6");
vo.setPhone("01011111111");
vo.setEmail("asdas@asd.com");
dao.create(vo);
} catch (Exception e) {
// TODO: handle exception
}
}
@Test
public void readGenericTest(){
try(SqlSession session = sqlMapper.openSession()) {
GenericDAO<MemberVO, String> dao = new GenericDAO<MemberVO, String>("org.ph.member.MemberMapper");
System.out.println(dao.read("leepan6"));
} catch (Exception e) {
e.printStackTrace();
}
}
'코딩 > WEB' 카테고리의 다른 글
Spring 설정 -- 2 Mybatis 연동하기 (0) | 2014.10.14 |
---|---|
MyBatis DynamicSQL Select 문 예제(XML) (0) | 2014.10.14 |
Web 예제: SQLExecutor(익명 클래스) 와 TimeDAO (jsp로 시간 나오게 하기) (0) | 2014.09.30 |
Web Project 전 기본 세팅 (0) | 2014.09.30 |
Eclipse Tomcat 서버 시작 문제. (0) | 2014.09.23 |