본문 바로가기

MyBatis

MyBatis 어노테이션 사용해서 사용하기

1.Configuration.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>


<!-- DB접속정보 값을 가지고 있는 파일 설정 -->

<properties resource="pack/mybatis/db.properties" />


<!-- DB접속 정보 셋팅 -->

<environments default="development">

<environment id="development">

<transactionManager type="JDBC" />

<dataSource type="POOLED">

<property name="driver" value="${driver}" />

<property name="url" value="${url}" />

<property name="username" value="${username}" />

<property name="password" value="${password}" />

</dataSource>

</environment>

</environments>

</configuration>


2.SqlMapConfig.java


import java.io.Reader;

import org.apache.ibatis.io.Resources;

import org.apache.ibatis.session.SqlSessionFactory;

import org.apache.ibatis.session.SqlSessionFactoryBuilder;


public class SqlMapConfig {

private static SqlSessionFactory sqlSession;


static {

String resource = "pack/mybatis/Configuration.xml";

try {

Reader reader = Resources.getResourceAsReader(resource);

sqlSession = new SqlSessionFactoryBuilder().build(reader);

reader.close();

Class[] mapper = {pack.business.SqlMapperInter.class};

for(Class m : mapper){

sqlSession.getConfiguration().addMapper(m); 

}

} catch (Exception e) {

System.out.println("SqlMapConfig 오류 : " + e);

}

}


public static SqlSessionFactory getSqlSession() {

return sqlSession;

}

}


3.SqlMapperInter.java


import java.util.List;


import org.apache.ibatis.annotations.Delete;

import org.apache.ibatis.annotations.Insert;

import org.apache.ibatis.annotations.Select;

import org.apache.ibatis.annotations.Update;


public interface SqlMapperInter {

@Select("select * from membertab")

public List<DataDto> selectDataAll();

@Select("select * from membertab where id=#{id}")

public DataDto selectDataById(String id);

@Insert("Insert into membertab values(#{id},#{name},#{passwd},sysdate)")

public int insertData(DataDto dto);

@Update("update membertab set name=#{name} where id=#{id}")

public int updateData(DataDto dto);

@Delete("delete from emebertab where id=#{id}")

public int deleteData(String id);

}


4.ProcessDao.java


import java.util.*;


import org.apache.ibatis.session.SqlSession;

import org.apache.ibatis.session.SqlSessionFactory;


import pack.mybatis.SqlMapConfig;


public class ProcessDao {

private SqlSessionFactory factiory = SqlMapConfig.getSqlSession();

private SqlSession sqlSession = factiory.openSession(); 

SqlMapperInter inter = (SqlMapperInter)sqlSession.getMapper(SqlMapperInter.class);

public ArrayList<DataDto> selectDataAll() {

ArrayList<DataDto> list=null;

try {

list = (ArrayList)inter.selectDataAll(); //인터페이스의 메소드 호출

} catch (Exception e) {

e.printStackTrace();

} finally {

sqlSession.close();

}

return list;

}