美文网首页
接口式编程

接口式编程

作者: 寒风凛凛 | 来源:发表于2018-06-15 23:54 被阅读0次

    MyBatis接口式编程

    一、原始方法:

    1.编写sql映射文件

    <!-- sql映射文件 -->
    <mapper namespace="org.test.example.ProductMapper">
        <select id="selectProduct" resultType="mytest.dao.Product">
            SELECT * FROM product p WHERE p.id = #{id};
        </select>
    </mapper>
    

    2.通过sql映射文件中namespace和id属性来定位Sql的位置,使用SqlSession对象的selectOne方法传递需要的参数arg并执行指定位置的Sql语句。

    public class MyBatisTest{
        public void MyTest(){
            String resource = "mybatis-config.xml";
            IntputStream intputStream = Resources.getResourceAsStream();
            SqlSessionFactory factory = newSqlSessionFactoryBuilder().bulid(intputStream);
            SqlSession sqlSession = factory.openSession();
            /** selectOne(String statement, Object parameter):
             *     statement :即sql映射文件中的namespace和id构成:namespace.id
             *     parameter :传递给sql映射文件的值
             */
            Product p = sqlSession.selectOne("org.test.example.ProductMapper.selectProduct", 1L);
        }
    }
    
    

    该方法直接通过sql映射文件中namespace和id属性来定位Sql的位置,要使用不同的方法,要改变id的值,看起来很不简洁,不够面向对象。

    二、接口式编程

    1.创建Mapper接口,并定义一个getProductById方法,用来通过id获取product对象。

    public interface ProductMapper {
        Product getProductById(Long id);
    }
    

    2.sql映射文件中的namespace属性为Mapper接口的全限定名,id为Mapper接口中对应的方法

    <!-- sql映射文件 -->
    <mapper namespace="mytest.dao.ProductMapper">
        <select id="getProductById" resultType="mytest.dao.Product">
            SELECT * FROM product p WHERE p.id = #{id};
        </select>
    </mapper>
    

    3.调用sqlSession对象中的getMapper(Class<T> type)方法来绑定Mapper接口,并获取Mapper对象。Mapper对象拥有接口中的方法,可直接使用,例如:使用getProductById方法从数据库中获取 id= 1 的Product对象。

    public class MyBatisTest{
        public void MyTest(){
            String resource = "mybatis-config.xml";
            IntputStream intputStream = Resources.getResourceAsStream();
            SqlSessionFactory factory = newSqlSessionFactoryBuilder().bulid(intputStream);
            SqlSession sqlSession = factory.openSession();
            /** getMapper(Class<T> type)
                type: Mapper interface class.传入Mapper接口class绑定接口
             */
            ProductMapper mapper = sqlSession.getMapper(ProductMapper.class);
            Product p = mapper.getProductById(1L);
        }
    }
    

    总结:比起原始方式,接口式编程的方法调用更加直观,更加面向对象,提高了可读性和可操作性。

    相关文章

      网友评论

          本文标题:接口式编程

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