프로그래머호이잇

mybatis 연동 방법 본문

java

mybatis 연동 방법

호이잇! 2017. 10. 16. 16:40

pom.xml


<!-- Database Connection -->

<dependency>

   <groupId>org.springframework</groupId>

   <artifactId>spring-jdbc</artifactId>

   <version>${org.springframework-version}</version>

</dependency>

 

<!-- Mybatis -->

<dependency>

      <groupId>org.mybatis</groupId>

      <artifactId>mybatis-spring</artifactId>

      <version>1.2.2</version>

    </dependency>

    <dependency>

      <groupId>org.mybatis</groupId>

      <artifactId>mybatis</artifactId>

      <version>3.1.1</version>

    </dependency>

    <!-- Mysql -->

    <dependency>

      <groupId>mysql</groupId>

      <artifactId>mysql-connector-java</artifactId>

      <version>5.1.21</version>

    </dependency>

    <!-- dbcp -->

    <dependency>

   <groupId>commons-dbcp</groupId>

   <artifactId>commons-dbcp</artifactId>

   <version>1.4</version>

</dependency>

 

 

root-context.xml

<bean id="dataSourceMySQL" class="org.apache.commons.dbcp.BasicDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver" />

    <property name="url" value="jdbc:mysql://DB HOST:3306/디비명"/>

    <property name="username" value="아이디"/>

    <property name="password" value="패스워드"/>

</bean>    

 

<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="dataSource" ref="dataSourceMySQL"/>

        <property name="configLocation" value="/WEB-INF/config/mybatisConfig.xml"/>

        <property name="mapperLocations" value="classpath*:패키지/*.xml" />

</bean>

<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

  <property name="basePackage" value="패키지" />

</bean>

<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">

        <constructor-arg index="0" ref="sqlSessionFactory"/>

</bean>

 

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

        <property name="dataSource" ref="dataSourceMySQL"/>

</bean>

 

 

UserDAO.java

public interface UserDAO {

public String getUserID();

 

}

 

User.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="패키지.UserDAO">

 

<select id="getUserID" resultType="String">

select id from user where seq = 1;

</select>

 

</mapper>

 

 

요런식으로 하면 Interface 정의 만으로 사용 가능함!!