mybatis_mapper动态代理

mapper的的动态代理

抛开接口的实现类,直接通过dao接口来定位到mappper中的SQL语句

1:修改StudentMapper.xml文件中的mapper标签的namespace属性

(mybatis会将当前的mapper.xml文件与StudentDao对应上)

<mapper namespace="com.doaoao.dao.StudentDao"

2:需要将StudentDao接口中的方法名要与 StudentMapper.xml 文件中的id名称对应上

// 接口
public interface StudentDao {
    void insertStudent(Student student);
    void deleteStudent(int id);
    void updateStudent(Student student);
    List<Student> selectAllStudents();
    Student selectStudentById(int id);
    Student selectStudentByAddress(int id);
}

// id名称
    <insert id="insertStudent" parameterType="com.doaoao.bean.Student">    ...      </insert>
<delete id="deleteStudent">    ... </delete>
<update id="updateStudent">    ... </update> <select id="selectAllStudents" resultType="student">    ... </select>
<select id="selectStudentById" resultType="student">    ... </select>

 3:不需要实现类,但在测试类中还是得获取SqlSession对象

// 执行测试方法之前会执行该方法
    @Before
    public void init(){
        sqlSession = MyBatisUtil.getSqlSession();
        studentDao = sqlSession.getMapper(StudentDao.class);  // 通过该方法可以获取StudentDao对象
    }

    // 方法执行完成后需要关闭sqlSession
    @After
    public void closeSession(){
        if(sqlSession != null){
            sqlSession.close();
        }
    }
  // 下面代码省略,与之前相同

注:将dao的实现类删除之后,mybatis底层只会调用selectOne()或selectList()方法。而框架选择方法的标准是dao层方法中用于接收返回值的对象类型。若接收类型为 List,则自动选择 selectList()方法;否则,自动选择 selectOne()方法。

本笔记参考自:小猴子老师教程 http://www.monkey1024.com

猜你喜欢

转载自www.cnblogs.com/Doaoao/p/10704627.html