美文网首页
MyBatis4-mapper代理开发规范&实现

MyBatis4-mapper代理开发规范&实现

作者: 我相信你爱过gg | 来源:发表于2017-03-14 00:01 被阅读397次

    思路:我们只需要写 mapper 接口(相当于 dao 接口),而不需要实现接口.在编写 mapper.xml 映射文件.

    开发规范

    注:mybatis 可以自动生成 mapper 接口的实现类代理对象.

    第一步

    在 mapper.xml 中 namespace 的值要为mapper 接口的包名+接口名.

    <mapper namespace="cc.ibadboy.mybatis.mapper.UserMapper">
    
    </mapper>
    
    第二步
    public interface UserMapper {
        public String findById(int id);
    }
    

    mapper.java接口中的方法名要和 mapper.xml映射文件中的 id 值一样.

    <select id="findById" resultType="String" parameterType="int">
    </select>
    
    第三步
    public interface UserMapper {
        public String findById(int id);
    }
    

    mapper.java接口中的方法参数要和 mapper.xml映射文件中的 parameterType 值一样.

    <select id="findById" resultType="String" parameterType="int">
    </select>
    
    第四步
    public interface UserMapper {
        public String findById(int id);
    }
    

    mapper.java接口中的方法返回值类型要和 mapper.xml映射文件中的 resultType 值一样.

    <select id="findById" resultType="String" parameterType="int">
    </select>
    

    实现

    //这几个步骤是必须的,因为必须要得到SqlSessionFactory
    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession session = sqlSessionFactory.openSession();
    
    //创建Mapper代理对象
    UserMapper userMapper = session.getMapper(UserMapper.class);
    
    //通过接口调用代理对象中的方法.
    String userName = userMapper.findById(1);
    
    System.out.println(userName);
    session.close();
    

    原理:其实代理对象内部调用 selectOne 或 selectList


    补充知识

    别名

    <typeAliases>
        <package name=""></package>
        <typeAlias type="" alias=""></typeAlias>
    </typeAliases>
    

    package:写包路径,别名就为包下的类名.
    typeAlias:包路径与类名,别名alias指定.
    注:别名在使用的时候是不区分大小写的.

    相关文章

      网友评论

          本文标题:MyBatis4-mapper代理开发规范&实现

          本文链接:https://www.haomeiwen.com/subject/poaqnttx.html