把mybatis当做工具类解析sql和处理preparedStatement

package com.lenovoar.shtest;

import com.lenovoar.shtest.dao.UserDao;
import lombok.val;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.Configuration;
import org.junit.Test;

import javax.annotation.Resource;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * @Description :  java类作用描述
 * @Author :  song_hao
 * @CreateDate :  2019/10/18 15:35
 */
//@RunWith(SpringRunner.class)
//@SpringBootTest
public class SampleTest {

    // MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/mp?useSSL=false&serverTimezone=UTC";

    // MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL
//    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
//    static final String DB_URL = "jdbc:mysql://localhost:3306/mp?useSSL=false&serverTimezone=UTC";


    // 数据库的用户名与密码,需要根据自己的设置
    static final String USER = "root";
    static final String PASS = "root";
//
//    @Resource
//    private UserMapper userMapper;
//
//    @Test
//    public void testSelect() {
//        System.out.println(("----- selectAll method test ------"));
//        List userList = userMapper.selectList(null);
//        Assert.assertEquals(5, userList.size());
//        userList.forEach(System.out::println);
//        System.out.printf(userMapper.getUserByName("").toString());
//    }
//
//    @Test
//    public void  pageTest(){
//        Page page = new Page<>();
//        page.setCurrent(3).setSize(2);
//        QueryWrapper wrapper = new QueryWrapper<>();
//        wrapper.eq("name", "Sandy");
//        IPage userIPage = userMapper.selectPage(page, null);
//        List records = userIPage.getRecords();
//        records.forEach(System.out::println);
//    }

    @Resource
    private UserDao userDao;

    @Test
    public void test1() {
        ArrayList<String> ids = new ArrayList<>();
        ids.add("1");
        ids.add("2");
        userDao.getList("song", ids);
    }

    @Test
    public void test2() throws FileNotFoundException {


        Connection conn = null;
        PreparedStatement preparedStatement = null;
        try {
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            System.out.println("实例化Statement对象...");


            //横切开始
            Configuration configuration = new Configuration();
            val xmlMapperBuilder = new XMLMapperBuilder(
                    new FileInputStream("E:\\Workspace\\mp\\src\\main\\resources\\mapper\\UserDao.xml"),
                    configuration,
                    "E:\\Workspace\\mp\\src\\main\\resources\\mapper\\UserDao.xml",
                    configuration.getSqlFragments());
            xmlMapperBuilder.parse();
            MappedStatement getUser = configuration.getMappedStatement("getUser");
            HashMap<String, String> map = new HashMap<>();
            map.put("username", "song");
            map.put("password", "");
            BoundSql boundSql = getUser.getSqlSource().getBoundSql(map);
            System.out.println(boundSql.getSql());
            //横切结束

            String sql;
            sql = boundSql.getSql();
            preparedStatement = conn.prepareStatement(sql);

            //横切开始
            Object parameterObject = boundSql.getParameterObject();
            ParameterHandler parameterHandler = configuration.newParameterHandler(getUser, parameterObject, boundSql);
            parameterHandler.setParameters(preparedStatement);
            //横切结束

            ResultSet rs = preparedStatement.executeQuery();

            // 展开结果集数据库
            while (rs.next()) {
                String username = rs.getString("username");
                String password = rs.getString("password");
                System.out.println(username + "::" + password);
            }
            // 完成后关闭
            rs.close();
            preparedStatement.close();
            conn.close();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (preparedStatement != null) preparedStatement.close();
            } catch (SQLException se2) {
            }// 什么都不做
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");


//        Configuration configuration = new Configuration();
//        val xmlMapperBuilder = new XMLMapperBuilder(new FileInputStream("E:\\Workspace\\mp\\src\\main\\resources\\mapper\\UserDao.xml"), configuration, "E:\\Workspace\\mp\\src\\main\\resources\\mapper\\UserDao.xml", configuration.getSqlFragments());
//        xmlMapperBuilder.parse();
//        MappedStatement getUser = configuration.getMappedStatement("getUser");
//        HashMap map = new HashMap<>();
//        map.put("username", "song");
//        map.put("password", "");
//        System.out.println(getUser.getSqlSource().getBoundSql(map).getSql());

//
//
//        ArrayList ids = new ArrayList<>();
//        ids.add("1");
//        ids.add("2");
//
//        MappedStatement ms = configuration.getMappedStatement("getList");
//        HashMap map1 = new HashMap<>();
//        map1.put("password", "song");
//        map1.put("list", ids);
//        BoundSql boundSql = ms.getSqlSource().getBoundSql(map1);
//        System.out.println(boundSql.getSql());
//        Object parameterObject = boundSql.getParameterObject();
//        ParameterMap parameterMap = ms.getParameterMap();
//        MetaObject metaObject = configuration.newMetaObject(parameterObject);
//        ParameterHandler parameterHandler = configuration.newParameterHandler(ms, parameterObject, boundSql);
//        parameterHandler.setParameters();
//        System.out.println(parameterHandler.getClass());
//        System.out.println(xmlMapperBuilder);
//        System.out.println(configuration);
    }


    /**
     * 测试循环
     */
    @Test
    public void test3() {


        Connection conn = null;
        PreparedStatement preparedStatement = null;
        try {
            // 注册 JDBC 驱动
            Class.forName(JDBC_DRIVER);

            // 打开链接
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            // 执行查询
            System.out.println("实例化Statement对象...");


            //横切开始
            Configuration configuration = new Configuration();
            val xmlMapperBuilder = new XMLMapperBuilder(
                    new FileInputStream("E:\\Workspace\\mp\\src\\main\\resources\\mapper\\UserDao.xml"),
                    configuration,
                    "E:\\Workspace\\mp\\src\\main\\resources\\mapper\\UserDao.xml",
                    configuration.getSqlFragments());
            xmlMapperBuilder.parse();
            MappedStatement getList = configuration.getMappedStatement("getList");

            ArrayList<String> ids = new ArrayList<>();
            ids.add("1");
            ids.add("2");

            HashMap<String, Object> map = new HashMap<>();
            map.put("password", "song");
            map.put("list", ids);

            BoundSql boundSql = getList.getSqlSource().getBoundSql(map);
            System.out.println(boundSql.getSql());
            //横切结束

            String sql;
            sql = boundSql.getSql();
            preparedStatement = conn.prepareStatement(sql);

            //横切开始
            Object parameterObject = boundSql.getParameterObject();
            ParameterHandler parameterHandler = configuration.newParameterHandler(getList, parameterObject, boundSql);
            parameterHandler.setParameters(preparedStatement);
            //横切结束

            ResultSet rs = preparedStatement.executeQuery();

            // 展开结果集数据库
            while (rs.next()) {
                String username = rs.getString("username");
                String password = rs.getString("password");
                System.out.println(username + "::" + password);
            }
            // 完成后关闭
            rs.close();
            preparedStatement.close();
            conn.close();
        } catch (SQLException se) {
            // 处理 JDBC 错误
            se.printStackTrace();
        } catch (Exception e) {
            // 处理 Class.forName 错误
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (preparedStatement != null) preparedStatement.close();
            } catch (SQLException se2) {
            }// 什么都不做
            try {
                if (conn != null) conn.close();
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
        System.out.println("Goodbye!");


    }


}

<?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.lenovoar.shtest.dao.UserDao">


    <select id="getUser" resultType="com.lenovoar.shtest.entity.User">
        select * from user where username = #{username}
        <if test="password != null and password != ''">
            and password = #{password}
        </if>
    </select>


    <select id="getList" parameterType="java.util.Map"  resultType="com.lenovoar.shtest.entity.User">
        select * from user where
        <if test="password != null and password != ''">
            password = #{password}
        </if>
        <if test="list!= null">
            and id in
            <foreach item="item" index="index" collection="list" open="(" close=")" separator=",">
                #{item}
            </foreach>
        </if>
    </select>


</mapper>

你可能感兴趣的:(源码系列)