Where The Streets Have No Name

mybatis & mysql 연동 본문

Developement/Java

mybatis & mysql 연동

highheat 2010. 8. 12. 16:36

mybatisConf.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="com.mysql.jdbc.Driver" />
				<property name="url" value="jdbc:mysql://localhost/test" />
				<property name="username" value="root" />
				<property name="password" value="9981" />
			</dataSource>
		</environment>
	</environments>
	<mappers>
		<mapper resource="mybatis/logMapper.xml" />		
	</mappers>
</configuration>

logMapper.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="logMapper">
	<select id="selectLog" parameterType="int" resultType="mybatis.Log">
		select *
		from apache_log 
		where seq = #{id}
 </select>
</mapper>

DBFactory.java

package mybatis;

import java.io.IOException;
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 DBFactory {
	
	private static DBFactory instance = new DBFactory();
	private SqlSessionFactory ssf;
	
	public static DBFactory getInstance(){
		return instance;
	}
	
	private DBFactory(){
		String resource = "mybatis/mybatisConf.xml";
		try {
			Reader reader = Resources.getResourceAsReader(resource);
			ssf = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public SqlSession openSession() {		
		return ssf.openSession();
	}
}

Test3.java

package mybatis;

import org.apache.ibatis.session.SqlSession;

public class Test3 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {

		DBFactory dbf = DBFactory.getInstance();
		
		try {			
			SqlSession session = dbf.openSession();
			try {
				Log log = (Log) session.selectOne("logMapper.selectLog", 47301);
				System.out.println(log);
			} finally {
				session.close();
			}
		} catch (Exception e) {			
			e.printStackTrace();
		}
	}

}