zoukankan      html  css  js  c++  java
  • 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();
            }
        }
    }
  • 相关阅读:
    一手遮天 Android
    一手遮天 Android
    一手遮天 Android
    一手遮天 Android
    springcloud~feign POST form-url-encoded data
    java~和.net相通的DES-ECB加解密技术
    java的byte和C#的byte的不同之处
    spi~动态监控目录的jar实现热加载
    jboss( WildFly)上运行 springboot程序
    nc
  • 原文地址:https://www.cnblogs.com/zhangjianbing/p/8318913.html
Copyright © 2011-2022 走看看