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

  • 相关阅读:
    ActiveReport换页的判断(当设置了repeatstyle为OnPage)
    创建与删除SQL约束或字段约束。 http://www.cnblogs.com/hanguoji/archive/2006/11/17/563871.html
    在SQL Server 2005中实现表的行列转换
    ActiveReport,Detail隐藏的问题
    SQL Server identity列的操作方法
    「預り」の意味
    POJ 1595 Prime Cuts
    Hdu Graph’s Cycle Component
    POJ 3250 Bad Hair Day
    Hdu 1548 A strange lift(BFS)
  • 原文地址:https://www.cnblogs.com/amiezhang/p/9575378.html
Copyright © 2020-2023  润新知