1.pom.xml 에 mybatis 추가. (jdbc와 mysql도 추가)
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.2.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.8</version>
</dependency>
2. application-config.xml 에 dataSource추가
<context:annotation-config />
<context:component-scan base-package="my"/>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="0000" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations" value="classpath:my/*.xml" />
</bean>
<!--For MapperScan <mybatis:scan base-package="my" /> 스캔방식이 아직 동작안하는 듯 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="my"/>
</bean>
3. User table 접근을 위한 UserVo.java와 UserMapper.java
public class UserVo {
private String username;
private Integer age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
public interface UserMapper {
//public int getManCount();
UserVo getUser(String name);
}
4. UserMapper.xml 을 resources 밑에 my 밑에 추가
<mapper namespace="my.UserMapper">
<select id="getUser" resultType="my.UserVo">
SELECT username,age
FROM user
WHERE username=#{name}
</select>
</mapper>
5. TestService.java
@Service
public class TestService implements ITestService{
@Resource
private UserMapper userMapper;
public UserVo getUser(String name){
return userMapper.getUser(name);
}
}