在之前的文章中已经提及开发dao的方式,当初是单纯的mybatis开发,分为原始开发方式和基于mapper代理的方式,与Spring整合之后的开发同样是这两种方式,原始的开发方式需要程序员书写dao接口和实现类,而且会存在很多问题,比如【005】提到的。
本章主要介绍使用mapper代理进行dao的开发。
【1】早在mapper文件下新建UserMapper.java接口文件。关键代码:
public interface UserMapper {
//根据id查询用户信息
User findUserById(int id) throws Exception;
}
【2】修改配置文件resources\applicationContext.xml,加入如下代码:
<!--原始dao接口--> <!--<bean id="userDao" class="dao.UserDaoImpl">--> <!--<property name="sqlSessionFactory" ref="sqlSessionFactory"/>--> <!--</bean>--> <!--配置mapper--> <!--<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">--> <!--<property name="mapperInterface" value="mapper.UserMapper"/>--> <!--<property name="sqlSessionFactory" ref="sqlSessionFactory"/>--> <!--</bean>--> <!--通过mapperScannerConfigure进行mapper扫描--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="mapper"/> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> </bean>
【3】修改映射文件resources\sqlMap\User.xml
<mapper namespace="test"> <!-- 在 映射文件中配置很多sql语句 --> <!-- 需求:通过id查询用户表的记录 --> <!-- 通过 select执行数据库查询 id:标识 映射文件中的 sql 将sql语句封装到mappedStatement对象中,所以将id称为statement的id parameterType:指定输入 参数的类型,这里指定int型 #{}表示一个占位符号 #{id}:其中的id表示 接收输入 的参数,参数名称就是id,如果输入参数是简单类型,#{}中的参数名可以任意,可以value或其它名称 resultType:指定sql输出结果 的所映射的java对象类型,select指定resultType表示将单条记录映射成的java对象。--> <select id="findUserById" parameterType="int" resultType="po.User"> SELECT *FROM USER WHERE id=#{value} </select> </mapper>
【4】测试程序
public class UserMapperTest {
private ApplicationContext applicationContext;
//在setUp这个方法得到spring容器
@Before
public void setUp() throws Exception {
applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
}
@Test
public void testFindUserById() throws Exception {
UserMapper userMapper = (UserMapper) applicationContext.getBean("userMapper");
User user = userMapper.findUserById(1);
System.out.println(user);
}
}
【5】结果如下: