Mybatis搭建及使用

mybatis基本框架在这里插入图片描述

pom中记得改项目名

普通方法

测试文件or主方法:StudentTest

//        1.加载mybatis核心配置文件,获取SQLSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//    2.获取SQLSession对象,用它来执行sql
    SqlSession sqlSession = sqlSessionFactory.openSession();
//    3.执行sql  "namespace.id"
    List<Student> objects = sqlSession.selectList("");
//    4.通过sqlSession调用mapper的代理对象
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//	  4.处理数据
    System.out.println(students);
//    4.释放资源
    sqlSession.close();

映射文件:StudentMapper.xml

<!--命名空间  -->
<!-- 此时namespace可以随便取名 -->
<mapper namespace="com.itheima.mapper.StudentMapper">
    <!-- resultType查询结果的类型 返回的是对象就填对象类的路径名 没有返回值就不写  -->
<!--    1.查询表里所有的数据-->
    <select id="selectAll" resultType="com.itheima.pojo.Student">
        select * from student;
    </select>
</mapper>

mybatis-config.xml

        <!--加载sql映射文件-->
<!--        <mapper resource="StudentMapper.xml"/>-->

代理方法

定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
设置SQL映射文件的namespace属性为Mapper接口全限定名
在 Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致

测试文件or主方法:StudentTest

//        1.加载mybatis核心配置文件,获取SQLSessionFactory
    String resource = "mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//    2.获取SQLSession对象,用它来执行sql
    SqlSession sqlSession = sqlSessionFactory.openSession();
//    3.通过sqlSession调用mapper的代理对象 映射文件.class
    StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//    4.通过mapper调用定义的方法
    List<Student> students = mapper.selectAll();
//	  5.处理数据
    System.out.println(students);
//    6.释放资源
    sqlSession.close();

映射文件:StudentMapper.xml

<!--命名空间  -->
<!-- 此时namespace的名字必须设置SQL映射文件的namespace属性为Mapper接口全限定名  -->
<mapper namespace="com.itheima.mapper.StudentMapper">
    <!-- resultType查询结果的类型 返回的是对象就填对象类的路径名 没有返回值就不写  -->
<!--    1.查询表里所有的数据-->
    <select id="selectAll" resultType="com.itheima.pojo.Student">
        select * from student;
    </select>
</mapper>

mybatis-config.xml

        <!--加载sql映射文件-->
     <mapper>
	  <package name="com.itheima.mapper"/>
	  </mapper>

使用 https://www.json.cn/json/sql2java.html可以快速生成student字段

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值