手写 | mybatis框架

手写 | mybatis框架

定义的注解

在这里插入图片描述

/**
 * 自定义插入注解
 *
 * @author 孙一鸣 on 2020/3/2
 */
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtInsert {
    String value();
}

/**
 * @author 孙一鸣 on 2020/3/2
 * 自定义参数注解
 */
@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtParam {
    String value();
}

/**
 * @author 孙一鸣 on 2020/3/2
 */
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ExtSelect {

    String value();

}

Dao层接口:

public interface UserDao {
    @ExtInsert("insert into t_users(userName,userAge) values(#{userName},#{userAge})")
    public int insertUser(@ExtParam("userName") String userName, @ExtParam("userAge") Integer userAge);

    @ExtSelect("select * from User where userName=#{userName} and userAge=#{userAge} ")
    void selectUser(@ExtParam("userName") String name, @ExtParam("userAge") Integer userAge);

}

加载了mapper接口

/**
 * @author 孙一鸣 on 2020/3/2
 */
public class SqlSession {

    //给目标对象生成一个代理对象 加载了mapper接口
    public static <T> T getMepper(Class classz) {

        return (T) Proxy.newProxyInstance(classz.getClassLoader(),new Class[] { classz },new MyIvocationHandler(classz));
    }
}


public class MyInvocationHandlerMbatis implements InvocationHandler {
	private Object object;

	public MyInvocationHandlerMbatis(Object object) {
		this.object = object;
	}

	// proxy 代理对象 method拦截方法 args方法上的参数值
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		System.out.println("使用动态代理技术拦截接口方法开始");
		// 使用白话问翻译,@ExtInsert封装过程
		// 1. 判断方法上是否存在@ExtInsert
		ExtInsert extInsert = method.getDeclaredAnnotation(ExtInsert.class);
		if (extInsert != null) {
			return extInsert(extInsert, proxy, method, args);
		}
		// 2.查询的思路
		// 1. 判断方法上是否存 在注解
		ExtSelect extSelect = method.getDeclaredAnnotation(ExtSelect.class);
		if (extSelect != null) {
			// 2. 获取注解上查询的SQL语句
			String selectSQL = extSelect.value();
			// 3. 获取方法上的参数,绑定在一起
			ConcurrentHashMap<Object, Object> paramsMap = paramsMap(proxy, method, args);
			// 4. 参数替换?传递方式
			List<String> sqlSelectParameter = SQLUtils.sqlSelectParameter(selectSQL);
			// 5.传递参数
			List<Object> sqlParams = new ArrayList<>();
			for (String parameterName : sqlSelectParameter) {
				Object parameterValue = paramsMap.get(parameterName);
				sqlParams.add(parameterValue);
			}
			// 6.将sql语句替换成?
			String newSql = SQLUtils.parameQuestion(selectSQL, sqlSelectParameter);
			System.out.println("newSQL:" + newSql + ",sqlParams:" + sqlParams.toString());

			// 5.调用jdbc代码底层执行sql语句
			// 6.使用反射机制实例对象### 获取方法返回的类型,进行实例化
			// 思路:
			// 1.使用反射机制获取方法的类型
			// 2.判断是否有结果集,如果有结果集,在进行初始化
			// 3.使用反射机制,给对象赋值

			ResultSet res = JDBCUtils.query(newSql, sqlParams);
			// 判断是否存在值
			if (!res.next()) {
				return null;
			}
			// 下标往上移动移位
			res.previous();
			// 使用反射机制获取方法的类型
			Class<?> returnType = method.getReturnType();
			Object object = returnType.newInstance();
			while (res.next()) {
				// 获取当前所有的属性
				Field[] declaredFields = returnType.getDeclaredFields();
				for (Field field : declaredFields) {
					String fieldName = field.getName();
					Object fieldValue = res.getObject(fieldName);
					field.setAccessible(true);
					field.set(object, fieldValue);
				}
				// for (String parameteName : sqlSelectParameter) {
				// // 获取参数值
				// Object resultValue = res.getObject(parameteName);
				// // 使用java的反射值赋值
				// Field field = returnType.getDeclaredField(parameteName);
				// // 私有方法允许访问
				// field.setAccessible(true);
				// field.set(object, resultValue);
				// }
			}
			return object;
		}

		return null;
	}

	private Object extInsert(ExtInsert extInsert, Object proxy, Method method, Object[] args) {
		// 方法上存在@ExtInsert,获取他的SQL语句
		// 2. 获取SQL语句,获取注解Insert语句
		String insertSql = extInsert.value();
		// System.out.println("insertSql:" + insertSql);
		// 3. 获取方法的参数和SQL参数进行匹配
		// 定一个一个Map集合 KEY为@ExtParamValue,Value 结果为参数值
		ConcurrentHashMap<Object, Object> paramsMap = paramsMap(proxy, method, args);
		// 存放sql执行的参数---参数绑定过程
		String[] sqlInsertParameter = SQLUtils.sqlInsertParameter(insertSql);
		List<Object> sqlParams = sqlParams(sqlInsertParameter, paramsMap);
		// 4. 根据参数替换参数变为?
		String newSQL = SQLUtils.parameQuestion(insertSql, sqlInsertParameter);
		System.out.println("newSQL:" + newSQL + ",sqlParams:" + sqlParams.toString());
		// 5. 调用jdbc底层代码执行语句
		return JDBCUtils.insert(newSQL, false, sqlParams);
	}

	private List<Object> sqlParams(String[] sqlInsertParameter, ConcurrentHashMap<Object, Object> paramsMap) {
		List<Object> sqlParams = new ArrayList<>();
		for (String paramName : sqlInsertParameter) {
			Object paramValue = paramsMap.get(paramName);
			sqlParams.add(paramValue);
		}
		return sqlParams;
	}

	private ConcurrentHashMap<Object, Object> paramsMap(Object proxy, Method method, Object[] args) {
		ConcurrentHashMap<Object, Object> paramsMap = new ConcurrentHashMap<>();
		// 获取方法上的参数
		Parameter[] parameters = method.getParameters();
		for (int i = 0; i < parameters.length; i++) {
			Parameter parameter = parameters[i];
			ExtParam extParam = parameter.getDeclaredAnnotation(ExtParam.class);
			if (extParam != null) {
				// 参数名称
				String paramName = extParam.value();
				Object paramValue = args[i];
				// System.out.println(paramName + "," + paramValue);
				paramsMap.put(paramName, paramValue);
			}
		}
		return paramsMap;
	}

	public Object extInsertSQL() {
		return object;
	}
}

工具类:
package com.sym.Util;

import java.sql.*;
import java.util.List;

/**
 * @author 孙一鸣 on 2020/3/2
 */

public final class JDBCUtils {

    private static String connect;
    private static String driverClassName;
    private static String URL;
    private static String username;
    private static String password;
    private static boolean autoCommit;

    /** 声明一个 Connection类型的静态属性,用来缓存一个已经存在的连接对象 */
    private static Connection conn;

    static {
        config();
    }

    /**
     * 开头配置自己的数据库信息
     */
    private static void config() {
        /*
         * 获取驱动
         */
        driverClassName = "com.mysql.jdbc.Driver";
        /*
         * 获取URL
         */
        URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8";
        /*
         * 获取用户名
         */
        username = "root";
        /*
         * 获取密码
         */
        password = "123456";
        /*
         * 设置是否自动提交,一般为false不用改
         */
        autoCommit = false;

    }

    /**
     * 载入数据库驱动类
     */
    private static boolean load() {
        try {
            Class.forName(driverClassName);
            return true;
        } catch (ClassNotFoundException e) {
            System.out.println("驱动类 " + driverClassName + " 加载失败");
        }

        return false;
    }

    /**
     * 专门检查缓存的连接是否不可以被使用 ,不可以被使用的话,就返回 true
     */
    private static boolean invalid() {
        if (conn != null) {
            try {
                if (conn.isClosed() || !conn.isValid(3)) {
                    return true;
                    /*
                     * isValid方法是判断Connection是否有效,如果连接尚未关闭并且仍然有效,则返回 true
                     */
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            /*
             * conn 既不是 null 且也没有关闭 ,且 isValid 返回 true,说明是可以使用的 ( 返回 false )
             */
            return false;
        } else {
            return true;
        }
    }

    /**
     * 建立数据库连接
     */
    public static Connection connect() {
        if (invalid()) { /* invalid为true时,说明连接是失败的 */
            /* 加载驱动 */
            load();
            try {
                /* 建立连接 */
                conn = DriverManager.getConnection(URL, username, password);
            } catch (SQLException e) {
                System.out.println("建立 " + connect + " 数据库连接失败 , " + e.getMessage());
            }
        }
        return conn;
    }

    /**
     * 设置是否自动提交事务
     **/
    public static void transaction() {

        try {
            conn.setAutoCommit(autoCommit);
        } catch (SQLException e) {
            System.out.println("设置事务的提交方式为 : " + (autoCommit ? "自动提交" : "手动提交") + " 时失败: " + e.getMessage());
        }

    }

    /**
     * 创建 Statement 对象
     */
    public static Statement statement() {
        Statement st = null;
        connect();
        /* 如果连接是无效的就重新连接 */
        transaction();
        /* 设置事务的提交方式 */
        try {
            st = conn.createStatement();
        } catch (SQLException e) {
            System.out.println("创建 Statement 对象失败: " + e.getMessage());
        }

        return st;
    }

    /**
     * 根据给定的带参数占位符的SQL语句,创建 PreparedStatement 对象
     *
     * @param SQL
     *            带参数占位符的SQL语句
     * @return 返回相应的 PreparedStatement 对象
     */
    private static PreparedStatement prepare(String SQL, boolean autoGeneratedKeys) {

        PreparedStatement ps = null;
        connect();
        /* 如果连接是无效的就重新连接 */
        transaction();
        /* 设置事务的提交方式 */
        try {
            if (autoGeneratedKeys) {
                ps = conn.prepareStatement(SQL, Statement.RETURN_GENERATED_KEYS);
            } else {
                ps = conn.prepareStatement(SQL);
            }
        } catch (SQLException e) {
            System.out.println("创建 PreparedStatement 对象失败: " + e.getMessage());
        }

        return ps;

    }

    public static ResultSet query(String SQL, List<Object> params) {

        if (SQL == null || SQL.trim().isEmpty() || !SQL.trim().toLowerCase().startsWith("select")) {
            throw new RuntimeException("你的SQL语句为空或不是查询语句");
        }
        ResultSet rs = null;
        if (params.size() > 0) {
            /* 说明 有参数 传入,就需要处理参数 */
            PreparedStatement ps = prepare(SQL, false);
            try {
                for (int i = 0; i < params.size(); i++) {
                    ps.setObject(i + 1, params.get(i));
                }
                rs = ps.executeQuery();
            } catch (SQLException e) {
                System.out.println("执行SQL失败: " + e.getMessage());
            }
        } else {
            /* 说明没有传入任何参数 */
            Statement st = statement();
            try {
                rs = st.executeQuery(SQL); // 直接执行不带参数的 SQL 语句
            } catch (SQLException e) {
                System.out.println("执行SQL失败: " + e.getMessage());
            }
        }

        return rs;

    }

    private static Object typeof(Object o) {
        Object r = o;

        if (o instanceof java.sql.Timestamp) {
            return r;
        }
        // 将 java.util.Date 转成 java.sql.Date
        if (o instanceof java.util.Date) {
            java.util.Date d = (java.util.Date) o;
            r = new java.sql.Date(d.getTime());
            return r;
        }
        // 将 Character 或 char 变成 String
        if (o instanceof Character || o.getClass() == char.class) {
            r = String.valueOf(o);
            return r;
        }
        return r;
    }

    public static boolean execute(String SQL, Object... params) {
        if (SQL == null || SQL.trim().isEmpty() || SQL.trim().toLowerCase().startsWith("select")) {
            throw new RuntimeException("你的SQL语句为空或有错");
        }
        boolean r = false;
        /* 表示 执行 DDL 或 DML 操作是否成功的一个标识变量 */

        /* 获得 被执行的 SQL 语句的 前缀 */
        SQL = SQL.trim();
        SQL = SQL.toLowerCase();
        String prefix = SQL.substring(0, SQL.indexOf(" "));
        String operation = ""; // 用来保存操作类型的 变量
        // 根据前缀 确定操作
        switch (prefix) {
            case "create":
                operation = "create table";
                break;
            case "alter":
                operation = "update table";
                break;
            case "drop":
                operation = "drop table";
                break;
            case "truncate":
                operation = "truncate table";
                break;
            case "insert":
                operation = "insert :";
                break;
            case "update":
                operation = "update :";
                break;
            case "delete":
                operation = "delete :";
                break;
        }
        if (params.length > 0) { // 说明有参数
            PreparedStatement ps = prepare(SQL, false);
            Connection c = null;
            try {
                c = ps.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                for (int i = 0; i < params.length; i++) {
                    Object p = params[i];
                    p = typeof(p);
                    ps.setObject(i + 1, p);
                }
                ps.executeUpdate();
                commit(c);
                r = true;
            } catch (SQLException e) {
                System.out.println(operation + " 失败: " + e.getMessage());
                rollback(c);
            }

        } else { // 说明没有参数

            Statement st = statement();
            Connection c = null;
            try {
                c = st.getConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            // 执行 DDL 或 DML 语句,并返回执行结果
            try {
                st.executeUpdate(SQL);
                commit(c); // 提交事务
                r = true;
            } catch (SQLException e) {
                System.out.println(operation + " 失败: " + e.getMessage());
                rollback(c); // 回滚事务
            }
        }
        return r;
    }

    /*
     *
     * @param SQL 需要执行的 INSERT 语句
     *
     * @param autoGeneratedKeys 指示是否需要返回由数据库产生的键
     *
     * @param params 将要执行的SQL语句中包含的参数占位符的 参数值
     *
     * @return 如果指定 autoGeneratedKeys 为 true 则返回由数据库产生的键; 如果指定 autoGeneratedKeys
     * 为 false 则返回受当前SQL影响的记录数目
     */
    public static int insert(String SQL, boolean autoGeneratedKeys, List<Object> params) {
        int var = -1;
        if (SQL == null || SQL.trim().isEmpty()) {
            throw new RuntimeException("你没有指定SQL语句,请检查是否指定了需要执行的SQL语句");
        }
        // 如果不是 insert 开头开头的语句
        if (!SQL.trim().toLowerCase().startsWith("insert")) {
            System.out.println(SQL.toLowerCase());
            throw new RuntimeException("你指定的SQL语句不是插入语句,请检查你的SQL语句");
        }
        // 获得 被执行的 SQL 语句的 前缀 ( 第一个单词 )
        SQL = SQL.trim();
        SQL = SQL.toLowerCase();
        if (params.size() > 0) { // 说明有参数
            PreparedStatement ps = prepare(SQL, autoGeneratedKeys);
            Connection c = null;
            try {
                c = ps.getConnection(); // 从 PreparedStatement 对象中获得 它对应的连接对象
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                for (int i = 0; i < params.size(); i++) {
                    Object p = params.get(i);
                    p = typeof(p);
                    ps.setObject(i + 1, p);
                }
                int count = ps.executeUpdate();
                if (autoGeneratedKeys) { // 如果希望获得数据库产生的键
                    ResultSet rs = ps.getGeneratedKeys(); // 获得数据库产生的键集
                    if (rs.next()) { // 因为是保存的是单条记录,因此至多返回一个键
                        var = rs.getInt(1); // 获得值并赋值给 var 变量
                    }
                } else {
                    var = count; // 如果不需要获得,则将受SQL影像的记录数赋值给 var 变量
                }
                commit(c);
            } catch (SQLException e) {
                System.out.println("数据保存失败: " + e.getMessage());
                rollback(c);
            }
        } else { // 说明没有参数
            Statement st = statement();
            Connection c = null;
            try {
                c = st.getConnection(); // 从 Statement 对象中获得 它对应的连接对象
            } catch (SQLException e) {
                e.printStackTrace();
            }
            // 执行 DDL 或 DML 语句,并返回执行结果
            try {
                int count = st.executeUpdate(SQL);
                if (autoGeneratedKeys) { // 如果企望获得数据库产生的键
                    ResultSet rs = st.getGeneratedKeys(); // 获得数据库产生的键集
                    if (rs.next()) { // 因为是保存的是单条记录,因此至多返回一个键
                        var = rs.getInt(1); // 获得值并赋值给 var 变量
                    }
                } else {
                    var = count; // 如果不需要获得,则将受SQL影像的记录数赋值给 var 变量
                }
                commit(c); // 提交事务
            } catch (SQLException e) {
                System.out.println("数据保存失败: " + e.getMessage());
                rollback(c); // 回滚事务
            }
        }
        return var;
    }

    /** 提交事务 */
    private static void commit(Connection c) {
        if (c != null && !autoCommit) {
            try {
                c.commit();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /** 回滚事务 */
    private static void rollback(Connection c) {
        if (c != null && !autoCommit) {
            try {
                c.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 释放资源
     **/
    public static void release(Object cloaseable) {

        if (cloaseable != null) {

            if (cloaseable instanceof ResultSet) {
                ResultSet rs = (ResultSet) cloaseable;
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (cloaseable instanceof Statement) {
                Statement st = (Statement) cloaseable;
                try {
                    st.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (cloaseable instanceof Connection) {
                Connection c = (Connection) cloaseable;
                try {
                    c.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

        }

    }

}
工具类2
package com.sym.Util;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 孙一鸣 on 2020/3/2
 */

public class SQLUtils {
    /**
     *
     * 获取Insert语句后面values 参数信息<br>
     * 作者: 每特教育-余胜军<br>
     * 联系方式:QQ644064779|WWW.itmayiedu.com<br>
     *
     * @param sql
     * @return
     */
    public static String[] sqlInsertParameter(String sql) {
        int startIndex = sql.indexOf("values");
        int endIndex = sql.length();
        String substring = sql.substring(startIndex + 6, endIndex).replace("(", "").replace(")", "").replace("#{", "")
                .replace("}", "");
        String[] split = substring.split(",");
        return split;
    }

    /**
     *
     * 获取select 后面where语句 作者: 每特教育-余胜军<br>
     * 联系方式:QQ644064779|WWW.itmayiedu.com<br>
     *
     * @param sql
     * @return
     */
    public static List<String> sqlSelectParameter(String sql) {
        int startIndex = sql.indexOf("where");
        int endIndex = sql.length();
        String substring = sql.substring(startIndex + 5, endIndex);
        String[] split = substring.split("and");
        List<String> listArr = new ArrayList<>();
        for (String string : split) {
            String[] sp2 = string.split("=");
            listArr.add(sp2[0].trim());
        }
        return listArr;
    }

    /**
     * 将SQL语句的参数替换变为?<br>
     * 作者: 每特教育-余胜军<br>
     * 联系方式:QQ644064779|WWW.itmayiedu.com<br>
     *
     * @param sql
     * @param parameterName
     * @return
     */
    public static String parameQuestion(String sql, String[] parameterName) {
        for (int i = 0; i < parameterName.length; i++) {
            String string = parameterName[i];
            sql = sql.replace("#{" + string + "}", "?");
        }
        return sql;
    }

    public static String parameQuestion(String sql, List<String> parameterName) {
        for (int i = 0; i < parameterName.size(); i++) {
            String string = parameterName.get(i);
            sql = sql.replace("#{" + string + "}", "?");
        }
        return sql;
    }

    public static void main(String[] args) {

        // String[] sqlParameter = sqlInsertParameter(sql);
        // for (String string : sqlParameter) {
        // System.out.println(string);
        // }

    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
手写实现MyBatis框架可以分为以下几个步骤: 1. 创建Maven工程并引入需要的依赖坐标。\[3\] 2. 编写Mybatis-config.xml配置文件,配置数据库连接信息、映射文件路径等。\[3\] 3. 创建XMLConfigBuilder类,用于解析Mybatis-config.xml配置文件。\[3\] 4. 创建Executor类,用于执行SQL语句并返回结果。\[3\] 5. 创建Mapper接口和对应的Mapper.xml文件,定义SQL语句和映射关系。\[3\] 6. 创建自定义的Mybatis类,包括读取配置文件、创建SqlSessionFactory、获取SqlSession等功能。\[3\] 7. 创建SqlSessionFactory接口和实现类,用于创建SqlSession对象。\[3\] 8. 创建SqlSession接口和实现类,用于执行SQL语句并返回结果。\[3\] 9. 创建Dao接口代理对象的类,用于动态生成Dao接口的实现类。\[3\] 10. 创建DataSourceUtil类,用于获取数据库连接。\[3\] 11. 编写测试类,测试自定义的Mybatis框架是否能够正常执行SQL语句并返回结果。\[3\] 通过以上步骤,我们可以手写实现一个简易的MyBatis框架,用于实现对数据库的操作。这个框架本质上是对JDBC进行了封装,并使用各种优化来解决使用JDBC的一些痛点问题。\[2\] #### 引用[.reference_title] - *1* *2* [二、手写MyBatis简易版框架](https://blog.csdn.net/weixin_36091079/article/details/129798863)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] - *3* [史上最全的自定义mybatis手写mybatis框架](https://blog.csdn.net/weixin_43570367/article/details/103244430)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^koosearch_v1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值