Mybatis面向接口式编程

Mybatis面向接口编程

1.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.dao.BookMapper">


  <select id="selectBook" resultType="Book" databaseId="mysql">
    select * from Book where id = #{id}
  </select>
  
  <insert id="insertBook">
      insert into book (title,price,publishDate) value(#{title},#{price},#{publishDate})
  </insert>
  
  <update id="updateBook">
      update book set title=#{title},price=#{price},publishDate=#{publishDate}
  </update>
  
  <delete id="deleteBook">
      delete from book where id=#{1}
  </delete>
  
  
</mapper>

namespace:接口全类名

resultType:返回值类型(起得别名)

databaseId:指定数据库厂商id

2.测试

public class Test {

    public static void main(String[] args) throws IOException {
        // 读取全局配置文件
        String resource = "conf/mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        // 获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        // 打开session
        SqlSession session = sqlSessionFactory.openSession();
        try {
            // 面向接口方式
            BookMapper bookMapper = session.getMapper(BookMapper.class);
            // 测试新增
            Book book = new Book(null, "jack", "2.1", "2018-01-19");
            boolean flag = bookMapper.insertBook(book);
            System.out.println(flag);
            // 一定得手动提交
            session.commit();
        } finally {
          // 关闭session
          session.close();
        }
    }
}

 

posted @ 2018-01-19 21:33  在谷歌上百度  阅读(326)  评论(0编辑  收藏  举报