Mybatis——Mapper代理开发(2)

上一篇文章中,获取查询语句对象时,
执行sql还是采用

 List<Student> users = sqlSession.selectList("ren.selectAll")

ren.selectAll依旧是硬编码的方式,本次使用mapper代理进行升级
大致改动流程:
在这里插入图片描述
1.首先,我们依然以数据库school中的student表为例,要操作student表,我们对应的xml文件(sql映射文件
)肯定是StudentMapper.xml;那么Mapper接口定义为StudentMapper.
并且放入同一目录下:
studentMapper接口的路径为:(字迹设定,两者保持一致即可)在这里插入图片描述
那么resources下面StudentMapper.xml的路径也要与接口保持一致
;resource下新建文件目录
在这里插入图片描述
最终两者在一个目录下
2.设置sql映射文件中的namespace
在这里插入图片描述

把namespace写为接口的全路径名

mapper namespace="com.itheima.mapper.StudentMapper">

3.Mapper接口中定义方法
在这里插入图片描述
studentMapper中的内容

package com.itheima.com.itheima.mapper;

import com.itheima.pojo.Student;

import java.util.List;

public interface StudentMapper {
    List<Student> selectAll();
}

4.编码启动


public class Mybatis_demo1 {
    public static void main(String[] args) throws IOException {
        //1.加载mybatis的核心配置文件,获取sqlSessionFactory
        //1. 加载mybatis的核心配置文件,获取 SqlSessionFactory
        String resource = "mybatis-config.xml";//前面写过的mybatis-config.xml文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

        //2. 获取SqlSession对象,用它来执行sql
        SqlSession sqlSession = sqlSessionFactory.openSession();
//        //3. 执行sql
//        List<Student> users = sqlSession.selectList("ren.selectAll");
        //3.采用mapper代理z执行sql
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> users = mapper.selectAll();

        System.out.println(users);
        //4. 释放资源
        sqlSession.close();
    }
}

5.注意事项
注意:studentMapper.xml文件要在mybatis-config.xml
文件中配置好
在这里插入图片描述
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值