实战(二)以接口的方式访问

1.在src_user源码目录下建立 com.yihaomen.mybatis.inter 这个包,并建立接口类 IUserOperation , 内容如下:

package com.yihaomen.mybatis.inter;
import com.yihaomen.mybatis.model.User;

public interface IUserOperation {    
    public User selectUserByID(int id);
    
}

 

注:方法名 selectUserByID 必须与 User.xml 里面配置的 select 的id 对应(<select id="selectUserByID")

2.重写测试代码

public static void main(String[] args) {
        SqlSession session = sqlSessionFactory.openSession();
        try {
            IUserOperation userOperation=session.getMapper(IUserOperation.class);
            User user = userOperation.selectUserByID(1);
            System.out.println(user.getUserAddress());
            System.out.println(user.getUserName());
        } finally {
            session.close();
        }
    }

 

3.将User.xmlde namespace里的路径换成接口的路径

<?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.yihaomen.mybatis.inter.IUserOperation">
<select id="selectUserByID" parameterType="int" resultType="User">
select * from `user` where id = #{id}
</select>
</mapper>

posted @ 2016-07-07 15:12  逝意遨游  阅读(192)  评论(0编辑  收藏  举报