Mybatis-Mapper代理开发

目的:1、解决原生硬编码的问题

2、便于后期执行sql

好处:首先他不依赖于字符串字面值,会更安全一点;其次,你的IDE有代码补全功能,那么代码补全可以帮你快速选择到映射好的sql语句

步骤:

1、定义与SQL映射文件同名的Mapper接口,并且将Mapper接口与SQL映射文件放置同一目录下

在包下创建接口UserMapper;在resources下创建目录和UserMapper的目录一致

注意:在resources下创建包的层次结构用“/"作为分割符号

2、设置SQL映射文件namespace属性为Mapper接口全限定名

之前:

<mapper namespace="test">  <!--namespace:名称空间-->
    <select id="selectAll" resultType="com.itheima.pojo.User">
        select * from tb_User;
    </select>
</mapper>

修改之后:

<mapper namespace="com.itheima.mapper.UserMapper">
    <select id="selectAll" resultType="com.itheima.pojo.User">
        select * from tb_User;
    </select>
</mapper>

3、在Mapper接口中定义方法,方法名就是SQL映射文件中的sql语句的id,并保持参数值类型和返回值类型一致

List<User> selectAll();

更改mybatis-config.xml中的mapper路径

<mappers>
    <mapper resource="com/itheima/mapper/UserMapper.xml"/>
</mappers>

4、编码

1.通过SqlSession的getMapper方法获取Mapper接口的代理对象

UserMapper userMapper=sqlSession.getMapper(UserMapper.class);

2.通过对应方法完成sql的执行

 List<User>  users= userMapper.select();

System.out.println(users);

sql.Session.close();//释放资源

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值