【Mybatis从0到1-016】Spring与MyBatis整合mapper开发DAO(推荐使用)

在之前的文章中已经提及开发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】结果如下:


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值