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下面的方法了

  • 相关阅读:
    蓝牙打印机的连接方法
    CE不能开机的可能情况
    手机性能指标的建议
    WINCE中使用键盘钩子的注意事项
    Wave接口开发注意事项
    解决唤醒屏不亮的问题之总结
    WM系统有用的注册表(研发人员使用)
    快速求解两个时间之间的天数
    测试SqlBulkCopy类批量插入数据
    Xml与DataTable相互转换方法
  • 原文地址:https://www.cnblogs.com/amiezhang/p/9575378.html
Copyright © 2011-2022 走看看