Mybatis 測試

單表增刪改查

新增

UserDao.xml

 <!--新增所有列-->
    <insert id="insert" keyProperty="id" useGeneratedKeys="true">
        insert into test.user(user_name, age, nick_name, create_time)
        values (#{userName}, #{age}, #{nickName}, #{createTime})
    </insert>

UserDao.java

    /**
     * 新增數據
     *
     * @param user 實例對象
     * @return 影響行數
     */
    int insert(User user);

UserDaoTest.java

    /**
     * 創建會話工廠
     * @return
     * @throws IOException
     */
    public SqlSessionFactory getSqlSessionFactory() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        return new SqlSessionFactoryBuilder().build(inputStream);
    }

    /**
     * 新增
     * @throws IOException
     */
    @Test
    public void insert() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        UserDao userDao = openSession.getMapper(UserDao.class);
        User user = new User();
        user.setUserName("halo");
        user.setNickName("Halos");
        user.setAge(22);
        int res = userDao.insert(user);
        System.out.println(res);
    }

日誌

Connected to the target VM, address: '127.0.0.1:55181', transport: 'socket'
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 685558284.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@28dcca0c]
DEBUG - ==>  Preparing: insert into test.user(user_name, age, nick_name, create_time) values (?, ?, ?, ?) 
DEBUG - ==> Parameters: halo(String), 22(Integer), Halos(String), null
DEBUG - <==    Updates: 1
1
DEBUG - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@28dcca0c]
Disconnected from the target VM, address: '127.0.0.1:55181', transport: 'socket'

修改

UserDao.xml

 <!--通過主鍵修改數據-->
    <update id="update">
        update test.user
        <set>
            <if test="userName != null and userName != ''">
                user_name = #{userName},
            </if>
            <if test="age != null">
                age = #{age},
            </if>
            <if test="nickName != null and nickName != ''">
                nick_name = #{nickName},
            </if>
            <if test="createTime != null">
                create_time = #{createTime},
            </if>
        </set>
        where id = #{id}
    </update>

UserDao.java

/**
     * 修改數據
     *
     * @param user 實例對象
     * @return 影響行數
     */
    int update(User user);

UserDaoTest.java

    /**
     * 修改
     * @throws IOException
     */
    @Test
    public void updateById() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        UserDao userDao = openSession.getMapper(UserDao.class);
        User user = new User();
        user.setId(3);
        user.setUserName("helo");
        user.setNickName("Helos");
        user.setAge(24);
        int res = userDao.update(user);
        System.out.println(res);
    }

日誌

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1686369710.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@6483f5ae]
DEBUG - ==>  Preparing: update test.user SET user_name = ?, age = ?, nick_name = ? where id = ? 
DEBUG - ==> Parameters: helo(String), 24(Integer), Helos(String), 3(Integer)
DEBUG - <==    Updates: 1
1

刪除

UserDao.xml

  <!--通過主鍵刪除-->
    <delete id="deleteById">
        delete from test.user where id = #{id}
    </delete>

UserDao.java

    /**
     * 通過主鍵刪除數據
     *
     * @param id 主鍵
     * @return 影響行數
     */
    int deleteById(Integer id);

UserDaoTest.java

  /**
     * 刪除
     * @throws IOException
     */
    @Test
    public void deleteById() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        UserDao userDao = openSession.getMapper(UserDao.class);
        int res = userDao.deleteById(3);
        System.out.println(res);
    }

日誌

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1739876329.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@67b467e9]
DEBUG - ==>  Preparing: delete from test.user where id = ? 
DEBUG - ==> Parameters: 3(Integer)
DEBUG - <==    Updates: 1
1

查詢

UserDao.xml

  <!--通過實體作爲篩選條件查詢-->
    <select id="queryAll" resultMap="UserMap">
        select
        id, user_name, age, nick_name, create_time
        from test.user
        <where>
            <if test="id != null">
                and id = #{id}
            </if>
            <if test="userName != null and userName != ''">
                and user_name = #{userName}
            </if>
            <if test="age != null">
                and age = #{age}
            </if>
            <if test="nickName != null and nickName != ''">
                and nick_name = #{nickName}
            </if>
            <if test="createTime != null">
                and create_time = #{createTime}
            </if>
        </where>
    </select>

UserDao.java

   /**
     * 通過實體作爲篩選條件查詢
     *
     * @param user 實例對象
     * @return 對象列表
     */
    List<User> queryAll(User user);

UserDaoTest.java

 /**
     * 按條件查詢所有
     * @throws IOException
     */
    @Test
    public void queryAll() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        UserDao userDao = openSession.getMapper(UserDao.class);
        User user = new User();
        user.setAge(24);
        List<User> list= userDao.queryAll(user);
        System.out.println(list.toString());
    }

日誌

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Cache Hit Ratio [com.kdgc.wangxianlin.dao.UserDao]: 0.0
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1475491159.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@57f23557]
DEBUG - ==>  Preparing: select id, user_name, age, nick_name, create_time from test.user WHERE age = ? 
DEBUG - ==> Parameters: 24(Integer)
DEBUG - <==      Total: 1
[User{id=4, userName='Tony', age=24, nickName='託尼', createTime=null}]

批量新增/刪除

批量新增

UserDao.xml

    <insert id="insertBatch" keyProperty="id" useGeneratedKeys="true">
        insert into test.user(user_name, age, nick_name, create_time)
        values
        <foreach collection="entities" item="entity" separator=",">
            (#{entity.userName}, #{entity.age}, #{entity.nickName}, #{entity.createTime})
        </foreach>
    </insert>

UserDao.java

    /**
     * 批量新增數據(MyBatis原生foreach方法)
     *
     * @param entities List<User> 實例對象列表
     * @return 影響行數
     */
    int insertBatch(@Param("entities") List<User> entities);

UserDaoTest.java

 /**
     * 批量插入
     * @throws IOException
     */
    @Test
    public void insertBatch() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        UserDao userDao = openSession.getMapper(UserDao.class);
        List<User> list= new ArrayList<>();
        User user = new User();
        user.setUserName("Tony");
        user.setNickName("託尼");
        user.setAge(24);

        list.add(user);
        User user2 = new User();
        user2.setUserName("Hony");
        user2.setNickName("哈尼");
        user2.setAge(22);
        list.add(user2);

        int res= userDao.insertBatch(list);
        System.out.println(res);
        openSession.commit();
    }

日誌

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 323326911.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@134593bf]
DEBUG - ==>  Preparing: insert into test.user(user_name, age, nick_name, create_time) values (?, ?, ?, ?) , (?, ?, ?, ?) 
DEBUG - ==> Parameters: Tony(String), 24(Integer), 託尼(String), null, Hony(String), 22(Integer), 哈尼(String), null
DEBUG - <==    Updates: 2
2
DEBUG - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@134593bf]

批量刪除

UserDao.xml

   <!-- void deleteBatch(List<Long> ids);-->
    <delete id="deleteBatch" parameterType="list">
        <!-- DELETE from user where id in(2,3,4,5) -->
        <!-- collection="list":遍歷的集合  index:索引  item:每次遍歷得到的對象 open:以什麼開始 close:以什麼關閉 separator:分隔符 -->
        DELETE from user where id in
        <foreach collection="list"  item="id" open="(" close=")" separator=",">
            #{id}
        </foreach>
    </delete>

UserDao.java

   /**
     * 批量刪除數據
     *
     * @param id 主鍵
     * @return 影響行數
     */
    int deleteBatch(List<Integer> id);

UserDaoTest.java

   /**
     * 批量刪除
     * @throws IOException
     */
    @Test
    public void deleteBatch() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        UserDao userDao = openSession.getMapper(UserDao.class);
        List<Integer> list= new ArrayList<>();
        list.add(3);
        list.add(4);
        int res= userDao.deleteBatch(list);
        System.out.println(res);
        openSession.commit();
    }

日誌

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Opening JDBC Connection
DEBUG - Created connection 323326911.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@134593bf]
DEBUG - ==>  Preparing: DELETE from user where id in ( ? , ? ) 
DEBUG - ==> Parameters: 3(Integer), 4(Integer)
DEBUG - <==    Updates: 2
2
DEBUG - Committing JDBC Connection [com.mysql.jdbc.JDBC4Connection@134593bf]

緩存

一級緩存

測試一

  • 先查詢 、在查詢第二次
  /**
     * 一級緩存查詢 測試
     * @throws IOException
     */
    @Test
    public void oneCache() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        try{
            UserDao userDao = openSession.getMapper(UserDao.class);
            // 第一次查詢
            User user = userDao.queryById(4);
            System.out.println("user"+ user.toString());

            // 第二次查詢
            User user1 = userDao.queryById(4);
            System.out.println("user1"+user1.toString());
        }finally {
            openSession.close();
        }
    }

日誌

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Cache Hit Ratio [com.kdgc.wangxianlin.dao.UserDao]: 0.0
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1209669119.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@481a15ff]
DEBUG - ==>  Preparing: select id, user_name, age, nick_name, create_time from test.user where id = ? 
DEBUG - ==> Parameters: 4(Integer)
DEBUG - <==      Total: 1
userUser{id=4, userName='Tony', age=24, nickName='託尼', createTime=null}
DEBUG - Cache Hit Ratio [com.kdgc.wangxianlin.dao.UserDao]: 0.0
user1User{id=4, userName='Tony', age=24, nickName='託尼', createTime=null}
DEBUG - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@481a15ff]
DEBUG - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@481a15ff]
DEBUG - Returned connection 1209669119 to pool.

測試二

  • 先查詢 、在更新、在查詢
/**
     * 一級緩存查詢 測試2
     * @throws IOException
     */
    @Test
    public void oneCache02() throws IOException {
        SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
        SqlSession openSession = sqlSessionFactory.openSession();
        try{
            UserDao userDao = openSession.getMapper(UserDao.class);
            // 第一次查詢
            User user = userDao.queryById(4);
            System.out.println("user"+ user.toString());

            // 更新操作
            user.setAge(18);
            userDao.update(user);

            // 第二次查詢
            User user1 = userDao.queryById(4);
            System.out.println("user1"+user1.toString());

        }finally {
            openSession.close();
        }
    }

日誌

DEBUG - Logging initialized using 'class org.apache.ibatis.logging.slf4j.Slf4jImpl' adapter.
DEBUG - Logging initialized using 'class org.apache.ibatis.logging.log4j.Log4jImpl' adapter.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - PooledDataSource forcefully closed/removed all connections.
DEBUG - Cache Hit Ratio [com.kdgc.wangxianlin.dao.UserDao]: 0.0
DEBUG - Opening JDBC Connection
DEBUG - Created connection 1209669119.
DEBUG - Setting autocommit to false on JDBC Connection [com.mysql.jdbc.JDBC4Connection@481a15ff]
DEBUG - ==>  Preparing: select id, user_name, age, nick_name, create_time from test.user where id = ? 
DEBUG - ==> Parameters: 4(Integer)
DEBUG - <==      Total: 1
userUser{id=4, userName='Tony', age=24, nickName='託尼', createTime=null}
DEBUG - ==>  Preparing: update test.user SET user_name = ?, age = ?, nick_name = ? where id = ? 
DEBUG - ==> Parameters: Tony(String), 18(Integer), 託尼(String), 4(Integer)
DEBUG - <==    Updates: 1
DEBUG - Cache Hit Ratio [com.kdgc.wangxianlin.dao.UserDao]: 0.0
DEBUG - ==>  Preparing: select id, user_name, age, nick_name, create_time from test.user where id = ? 
DEBUG - ==> Parameters: 4(Integer)
DEBUG - <==      Total: 1
user1User{id=4, userName='Tony', age=18, nickName='託尼', createTime=Sun Aug 14 22:21:25 CST 2022}
DEBUG - Rolling back JDBC Connection [com.mysql.jdbc.JDBC4Connection@481a15ff]
DEBUG - Resetting autocommit to true on JDBC Connection [com.mysql.jdbc.JDBC4Connection@481a15ff]
DEBUG - Closing JDBC Connection [com.mysql.jdbc.JDBC4Connection@481a15ff]
DEBUG - Returned connection 1209669119 to pool.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章