码迷,mamicode.com
首页 > 其他好文 > 详细

Mybatis面向接口式编程

时间:2018-01-19 22:24:29      阅读:195      评论:0      收藏:0      [点我收藏+]

标签:http   builder   out   stat   关闭   tty   接口   comm   post   

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();
        }
    }
}

 

Mybatis面向接口式编程

标签:http   builder   out   stat   关闭   tty   接口   comm   post   

原文地址:https://www.cnblogs.com/zhangjianbing/p/8318913.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!