将UserMapper.java和UserMapper.xml放在同一个目录下,是为了mapper的批量扫描
1.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必须和UserMapper.java类地址相同
<mapper namespace="com.chinglee.ssm.mapper.UserMapper">
<select id="findUserByIdMapper" parameterType="int" resultType="com.chinglee.ssm.po.User">
SELECT * FROM USER WHERE id=#{value}
</select>
</mapper>
2.UserMapper.java
package com.chinglee.ssm.mapper;
import com.chinglee.ssm.po.User;
/**
* Created by Administrator on 2017/11/2 0002.
*/
public interface UserMapper {
public User findUserByIdMapper(int id) throws Exception;
}
3.SqlMapConfig.xml配置批量加载mapper
<!--批量加载mapper
指定mapper接口的包名,mybatis自动扫描包下面所有mapper接口进行加载
遵循一些规范:需要将mapper接口类名和mapper.xml映射文件名称保持一致,且在一个目录中
前提:使用mapper代理的方法
-->
<package name="com.chinglee.ssm.mapper"/>
4.applicationContext.xml中实现mapper的sqlSessionFactory的批量注入。
<!-- mapper批量扫描,从mapper包中扫描出mapper接口,自动创建代理对象并且在spring容器中注册
遵循规范:将mapper.java和mapper.xml映射文件名称保持一致,且在一个目录中
自动扫描出来的mapper的bean的id为mapper类名(首字母小写)
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 指定扫描的包名,如果扫描多个包,每个包中间使用半角逗号分隔-->
<property name="basePackage" value="com.chinglee.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
5.测试
package com.chinglee.ssm.mapper;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* Created by Administrator on 2017/11/2 0002.
*/
public class UserMapperTest {
private ApplicationContext applicationContext;
@Before
public void setUp() throws Exception {
applicationContext=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}
@Test
public void findUserByIdMapper() throws Exception {
UserMapper userMapper= (UserMapper) applicationContext.getBean("userMapper");
userMapper.findUserByIdMapper(1);
}
}