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

 

posted @ 2018-09-02 21:20  张啊咩  阅读(1131)  评论(0编辑  收藏  举报