1
2.config/配置文件
config/mybatis/SqlMapConfig.xml
<!-- 加载映射文件 -->
<mappers>
<package name="com.app.ssm.mapper" />
</mappers>config/spring/applicationContext.xml
<!-- Mapper包实现类 -->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.app.ssm.mapper.UserMapper" />
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>3.src/ssm包
mapper接口
public interface UserMapper {
// R 根据id查询用户信息
public User findUserById(int id) throws Exception;
}mapper.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">
<!-- namespace命名空间,作用就是对sql进行分类化管理,理解sql隔离
注意:使用mapper代理方法开发,namespace有特殊重要的作用
-->
<mapper namespace="com.app.ssm.mapper.UserMapper">
<!-- R 根据id查询一条记录结果 -->
<select id="findUserById" parameterType="int" resultType="user">
SELECT * FROM USER WHERE id=#{value}
</select>
</mapper>4.test单元测试
package com.app.ssm.mapper;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.app.ssm.po.User;
/**
*@Title UserMapperTest.java
*@description TODO
*@time 2016年9月13日 下午3:49:43
*@author wyz
*@version 1.0
**/
public class UserMapperTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test
public void testFindUserById() throws Exception{
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.findUserById(1);
System.out.println(user);
}
}5
6
本文介绍如何在SSM框架中集成MyBatis,并通过配置文件设置Mapper接口及其实现,最后通过JUnit进行单元测试验证功能正确性。

被折叠的 条评论
为什么被折叠?



