• mybatis(1):入坑篇



    依赖

            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.4.0</version>
            </dependency>
            <!-- 测试数据库 -->
            <dependency>
                <groupId>org.hsqldb</groupId>
                <artifactId>hsqldb</artifactId>
                <version>2.3.4</version>
            </dependency>
    

    myBatis 配置

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE configuration
            PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
            "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <!-- 引入properties配置文件 -->
        <properties resource="jdbc.properties"/>
        <environments default="test">
            <environment id="test">
                <transactionManager type="JDBC" />
                <dataSource type="UNPOOLED">
                    <property name="driver" value="${hsqldb.driver}" />
                    <property name="url" value="${hsqldb.url}" />
                    <property name="username" value="${hsqldb.username}" />
                    <property name="password" value="${hsqldb.password}" />
                </dataSource>
            </environment>
        </environments>
        <mappers>
            <!-- mapping 配置: 加载 Mapper.xml 和 Mapper.class -->
            <mapper class="com.github.xsj.model.Mapper"/>
        </mappers>    
    </configuration>
    

    映射配置

    使用 Mapper wrapper

    package com.github.xsj.model;
    
    public class User {
    
        private Long id;   // id 使用 Long 类型而非 long
        private String name;
        ...
    }
    

    Wrapper:

    package com.github.xsj.model;
    
    public interface Mapper {
    
        User getUser(long id);
    
        void insertUser(User user);
    
        @Update("update users set name = #{name}")
        void updateUser(User user);
    
        @Delete("delete from users where id = #{id}")
        void deleteUser(long id);
    
    }
    

    映射文件: srcmain esourcescomgithubxsjmodelMapper.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.github.xsj.model.Mapper">
        <select id="getUser" resultType="com.github.xsj.model.User">
            select * from users where id = #{id}
        </select>
        <!-- get generated key! Note: keyColumn 之所以使用 ID 而非 id 是 hsqldb 将列名强行转换为大写所导致 -->
        <insert id="insertUser" useGeneratedKeys="true" keyProperty="id" keyColumn="ID">
              insert into users values(#{id}, #{name})
        </insert>
    </mapper>
    

    单元测试

    sql 脚本

    drop table users if exists;
    create table users (
      id INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 1, INCREMENT BY 1) primary key,
      name varchar(126) not null
    );
    insert into users(name) values('User1');
    

    样例

    public class BaseTest {
     
        private final static Logger log =  LoggerFactory.getLogger(BaseTest.class);
     
        private static SqlSessionFactory sqlSessionFactory;
     
        @BeforeClass
        public static void setUp() throws Exception{
            Reader reader = Resources.getResourceAsReader("mybatis-test-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
            // 数据初始化
            SqlSession session = sqlSessionFactory.openSession();
            Connection conn = session.getConnection();
            reader = Resources.getResourceAsReader("com/github/xsj/model/CreateDB.sql");
            ScriptRunner runner = new ScriptRunner(conn);
            runner.setLogWriter(new PrintWriter(System.out));
            runner.runScript(reader);
            reader.close();
            conn.close();
            session.close();
        }
     
        @Test
        public void selectTest() {
            SqlSession session = sqlSessionFactory.openSession();
            try {
                Mapper mapper = session.getMapper(Mapper.class);
                assertThat(mapper.getUser(1), is(notNullValue()));
            } finally {
                session.close();
            }
        }
        ...
    }
    

    源码: https://github.com/xsj24/mybaits-getStarted/tree/v1.0.0

  • 相关阅读:
    Web开发之编码与解码、签名、加密与解密
    深入解析单例线程安全问题
    PL/SQL&存储过程||存储函数&触发器
    oracle
    子查询中的NULL问题
    springmvc适配器的应用
    MySQL
    Django rest framework(5)----解析器
    Django rest framework(4)----版本
    1. Django每日一码 之原生View源码
  • 原文地址:https://www.cnblogs.com/xsj24/p/5996017.html
Copyright © 2020-2023  润新知