zoukankan      html  css  js  c++  java
  • Java_myBatis_xml代理写法

    这种开发方式只需要写好Mapper.xml和对应的Interface就可以了。

    1.编写Mapper.xml

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
    <mapper namespace="com.mavenTest.mybatis_mapper.StudentMapper">
        <select id="getStudentById" parameterType="int" resultType="com.mavenTest.mybatis_test.po.Student">
            select * from students_table where id = #{id}
        </select>
        <insert id="insertStudent" parameterType="com.mavenTest.mybatis_test.po.Student">
            insert into students_table(name,student_code,createTime,class_id,userId) values(#{name},#{student_code},#{createTime},#{class_id},#{userId})
        </insert>
    </mapper>

    2.编写interface

    package com.mavenTest.mybatis_mapper;
    
    import com.mavenTest.mybatis_test.po.Student;
    
    public interface StudentMapper {
        public Student getStudentById(int id) throws Exception;
        public void insertStudent(Student s) throws Exception;
    }

    就这两步其实就已经完成了开发,但是值得注意的是:

    1.xml中namespace要和interface的全名一致,如上面的“com.mavenTest.mybatis_mapper.StudentMapper”

    2.xml中的查询标签的Id要和interface的方法名一致,如上面的“getStudentById”和“insertStudent”

    3.xml中parameterType和interface方法的传参要一致,如上面的"int id"和parameterType="int"

    4.xml中resultType和interface方法的返回值类型要一致,如上面的"Student"和resultType="com.mavenTest.mybatis_test.po.Student"


    单元测试:

    public class StudentMapperTest {
    
        private SqlSessionFactory ssf;
    
        @Before
        public void before() throws IOException {
            String resources = "SqlMapConfig.xml";
            InputStream is = Resources.getResourceAsStream(resources);
            this.ssf = new SqlSessionFactoryBuilder().build(is);
        }
    
        @Test
        public void test() throws Exception {
            SqlSession ss = this.ssf.openSession();
            StudentMapper sm = ss.getMapper(StudentMapper.class);
            Student s = sm.getStudentById(869);
            System.out.println(s.getName());
        }
    
    }

    值得注意的是,怎么生成我们想要的mapper(可以直接调用它的方法来操作数据库)呢?

    我们其实还是要走:SqlSessionFactoryBuilder--build()-->SqlSessionFactory--openSession()-->SqlSession--getMapper()-->mapper

    得到mapper我们就可以直接使用之前interface定义好的方法了,不再需要我们直接使用SqlSession下面的方法了

  • 相关阅读:
    2019-2020-2 网络对抗技术 20175206李得琛 Exp5 信息搜集与漏洞扫描
    2019-2020-4 网络对抗技术 20175206李得琛 Exp4 恶意代码分析
    2019-2020-2 网络对抗技术 20175206李得琛 Exp3 免杀原理与实践
    2019-2020-2 网络对抗技术 20175206李得琛 Exp2 后门原理与实践
    2019-2020-2 网络对抗技术 20175206李得琛 Exp1 PC平台逆向破解
    ucos作业
    实现ls及ls的改进ls的实现
    stat命令的实现-mysate
    2019-2020-1 20175203 20175206 实验五 通讯协议设计
    第八周测试课下补交
  • 原文地址:https://www.cnblogs.com/amiezhang/p/9575378.html
Copyright © 2011-2022 走看看