手写MyBatis ORM框架
目标:
实现MyBatis
的基本功能。主要包括在方法中加入以下自定义注解、则获得相应的功能:
ChenInsert
实现添加数据的功能ChenQuery
实现查询数据的功能,如果有多条数据只返回第一条数据ChenQueryList
实现查询数据的功能,如果有多条数据返回全部数据ChenDelete
实现删除数据的功能ChenUpdate
实现更新数据的功能,返回更新后的对象ChenUpdateInt
实现更新数据的功能,返回更新的记录数ChenParam
定义参数注解,获取变量名称
实现:
思路:
自定义SqlSession
,完成动态代理拦截接口方法的功能。大致步骤如下:
- 首先判断方法上是否存在自定义注解。
- 如果没有自定义注解则直接结束,否则获取注解上的SQL语句。
- 然后获取方法上的参数,将参数名称和参数值绑定在一起。
- 然后将
mybatis
语法的SQL
语句替换成jdbc
的SQL语句。 - 接着调用
jdbc
代码底层执行sql
语句。 - 如果是基本类型则直接返回,如果是引用对象则使用反射机制实例对象,获取方法返回的类型,进行实例化返回给调用者。
一、前期准备
根据测试先行的敏捷方法,我们先搭好业务应用场景、实现自定义注解,并用自定义注解模拟对数据库的增删改查。先实现空方法,再对具体需求进行开发。
1、加入依赖
本项目MyBatisORM
是对数据库的操作,所以需要引入MySQL
驱动包、数据库连接池等jar
包。源码如下:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>handwritingproject</artifactId>
<groupId>com.njust</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>mybatischen</artifactId>
<dependencies>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<!-- 引入Spring-AOP等相关Jar -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>3.0.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
<!-- https://mvnrepository.com/artifact/asm/asm -->
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>3.3.1</version>
</dependency>
</dependencies>
</project>
2、自定义插入注解
定义ChenInsert
类,使得该注解的作用范围在方法上 。同时保证注解会在class
字节码文件中存在,在运行时可以通过反射获取到。设置value
属性值,为后面获取SQL
语句做准备。源码如下:
ChenInsert .java
package com.njust.mybatisorm.orm.annotation;
/**
* @author Chen
* @version 1.0
* @date 2020/4/2 8:37
* @description:
*/
import java.lang.annotation.*;
/**
* 自定义插入注解 <br>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ChenInsert {
String value();
}
3、自定义删除注解
定义ChenDelete
类,使得该注解的作用范围在方法上 。同时保证注解会在class
字节码文件中存在,在运行时可以通过反射获取到。设置value
属性值,为后面获取SQL
语句做准备。源码如下:
ChenDelete .java
package com.njust.mybatisorm.orm.annotation;
import java.lang.annotation.*;
/**
* 自定义删除注解 <br>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ChenDelete {
String value();
}
4、自定义更新注解
定义ChenUpdate
类,使得该注解的作用范围在方法上 。同时保证注解会在class
字节码文件中存在,在运行时可以通过反射获取到。设置value
属性值,为后面获取SQL
语句做准备。注意:该注解使得注解方法更新的返回值是更新后的实体对象。源码如下:
ChenUpdate .java
package com.njust.mybatisorm.orm.annotation;
import java.lang.annotation.*;
/**
* 自定义更新注解 <br>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ChenUpdate {
String value();
}
定义ChenUpdateInt
类,使得该注解的作用范围在方法上 。同时保证注解会在class
字节码文件中存在,在运行时可以通过反射获取到。设置value
属性值,为后面获取SQL
语句做准备。注意:该注解使得注解方法更新的返回值是成功更新的记录数,注意和上面的注解区别。源码如下:
ChenUpdateInt.java
package com.njust.mybatisorm.orm.annotation;
import java.lang.annotation.*;
/**
* 自定义更新注解 <br>
* 返回更新数量
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ChenUpdateInt {
String value();
}
5、自定义查询注解
定义ChenQuery
类,使得该注解的作用范围在方法上 。同时保证注解会在class
字节码文件中存在,在运行时可以通过反射获取到。设置value
属性值,为后面获取SQL
语句做准备。注意:该注解使得注解方法,如果有查询结果则返回查询结果的第一个值,注意和下面的注解区别。源码如下:
ChenQuery .java
package com.njust.mybatisorm.orm.annotation;
import java.lang.annotation.*;
/**
* 自定义查询注解 <br>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ChenQuery {
String value();
}
定义ChenQueryList
类,使得该注解的作用范围在方法上 。同时保证注解会在class
字节码文件中存在,在运行时可以通过反射获取到。设置value
属性值,为后面获取SQL
语句做准备。注意:该注解使得注解方法,如果有查询结果则返回全部查询结果,注意和上面的注解区别。源码如下:
ChenQueryList .java
package com.njust.mybatisorm.orm.annotation;
import java.lang.annotation.*;
/**
* 自定义查询注解 <br>
* 返回多个参数
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface ChenQueryList {
String value();
}
6、自定义参数注解
定义ChenParam
类,使得该注解的作用范围在参数上 。同时保证注解会在class
字节码文件中存在,在运行时可以通过反射获取到。设置value
属性值,为后面获取具体参数值做准备。源码如下:
ChenParam .java
package com.njust.mybatisorm.orm.annotation;
import java.lang.annotation.*;
/**
* 自定义参数注解<br>
*/
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ChenParam {
String value();
}
7、定义和数据库对应的实体类
定义User
类,和数据库属性对应,包括id
,用户名,年龄等基本属性。提供get()
和set()
方法实现对对象的操作,tostring()
方法可以不要,但是为了便于测试,我们此处将其加入进来。源码如下:
User .java
package com.njust.mybatisorm.entity;
public class User {
private Integer id;
private String userName;
private Integer userAge;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public Integer getUserAge() {
return userAge;
}
public void setUserAge(Integer userAge) {
this.userAge = userAge;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", userAge=" + userAge +
'}';
}
}
8、定义对数据库的操作接口
定义UserMapper
类,模拟mybatis
的操作方法,对数据库进行增删改查。源码如下:
UserMapper .java
package com.njust.mybatisorm.mapper;
import com.njust.mybatisorm.entity.User;
import com.njust.mybatisorm.orm.annotation.*;
import java.util.List;
public interface UserMapper {
@ChenInsert("insert into user(userName,userAge) values(#{userName1},#{userAge})")
public int insertUser(@ChenParam("userName1") String userName, @ChenParam("userAge") Integer userAge);
@ChenDelete("DELETE from user WHERE id=#{id}")
public int deleteUser(@ChenParam("id") Integer id);
@ChenQuery("select * from User where userName=#{userName} and userAge=#{userAge} ")
User selectUser(@ChenParam("userName") String name, @ChenParam("userAge") Integer userAge);
@ChenQueryList("select * from User where userName=#{userName} and userAge=#{userAge} ")
List<User> selectUserList(@ChenParam("userName") String name, @ChenParam("userAge") Integer userAge);
@ChenUpdate("UPDATE user set userName=#{userName} ,userAge=#{userAge} WHERE id=#{id} ")
User updateUser(@ChenParam("id") Integer id, @ChenParam("userName") String name, @ChenParam("userAge") Integer userAge);
@ChenUpdateInt("UPDATE user set userName=#{userName} ,userAge=#{userAge} WHERE id=#{id} ")
int updateUserInt(@ChenParam("id") Integer id, @ChenParam("userName") String name, @ChenParam("userAge") Integer userAge);
}
9、自定义动态代理方法
定义SqlSession
类,拦截代理接口,使用自定义ChenInvocationHandlerMybatis
拦截器对方法实际处理。源码如下:
SqlSession .java
package com.njust.mybatisorm.sql;
import com.njust.mybatisorm.orm.aop.ChenInvocationHandlerMybatis;
import java.lang.reflect.Proxy;
public class SqlSession {
// 加载Mapper接口
public static <T> T getMapper(Class classz) {
//loader: 用哪个类加载器去加载代理对象
//interfaces:动态代理类需要实现的接口
//h:动态代理方法在执行时,会调用h里面的invoke方法去执行
return (T) Proxy.newProxyInstance(classz.getClassLoader(), new Class[]{classz},
new ChenInvocationHandlerMybatis(classz));
}
}
10、自定义动态代理
定义ChenInvocationHandlerMybatiss
类,继承InvocationHandler
类,实现其代理拦截方法,这里我们要检测业务环境是否搭建成功,只是简单的拦截并输出。测试成功之后再实现具体的业务逻辑。源码如下:
ChenInvocationHandlerMybatiss .java
package com.njust.mybatisorm.orm.aop;
import com.njust.mybatisorm.orm.annotation.*;
import com.njust.mybatisorm.utils.JDBCUtils;
import com.njust.mybatisorm.utils.SQLUtils;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;
import java.lang.reflect.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import static com.njust.mybatisorm.utils.SQLUtils.getTableName;
/**
* 使用反射动态代理技术 拦截接口防范
*/
public class ChenInvocationHandlerMybatiss implements InvocationHandler {
private Object object;
public ChenInvocationHandlerMybatiss(Object object) {
this.object = object;
}
// proxy 代理对象 method拦截方法 args方法上的参数值
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("使用动态代理技术拦截接口方法开始");
// 使用白话问翻译,@ChenInsert封装过程
// 1. 判断方法上是否存在@ChenInsert
ChenInsert chenInsert = method.getDeclaredAnnotation(ChenInsert.class);
if (chenInsert != null) {
System.out.println("拦截到ChenInsert注解");
}
// 1. 判断方法上是否存 在删除注解
ChenDelete chenDelete = method.getDeclaredAnnotation(ChenDelete.class);
if (chenDelete != null) {
System.out.println("拦截到ChenDelete注解");
}
// 2.查询的思路
// 1. 判断方法上是否存 在查询注解
ChenQuery chenQuery = method.getDeclaredAnnotation(ChenQuery.class);
if (chenQuery != null) {
System.out.println("拦截到ChenQuery注解");
}
// 1. 判断方法上是否存 在查询注解
ChenQueryList chenQueryList = method.getDeclaredAnnotation(ChenQueryList.class);
if (chenQueryList != null) {
System.out.println("拦截到ChenQueryList注解");
}
/**
* 更新
*/
ChenUpdate chenUpdate = method.getDeclaredAnnotation(ChenUpdate.class);
if (chenUpdate != null) {
System.out.println("拦截到ChenUpdate注解");
}
/**
* 更新 返回更新数量
*/
ChenUpdateInt chenUpdateInt = method.getDeclaredAnnotation(ChenUpdateInt.class);
if (chenUpdateInt != null) {
System.out.println("拦截到ChenUpdateInt注解");
}
return new Object();
}
}
11、自定义测试类
定义TestOK
类,类似MyBatis
般操作数据库,这里节约时间,我只测试了selectUserList()
方法,其他方法类似。源码如下:
TestOK .java
package com.njust.mybatisorm;
import com.njust.mybatisorm.entity.User;
import com.njust.mybatisorm.mapper.UserMapper;
import com.njust.mybatisorm.sql.SqlSession;
import org.junit.Test;
import java.util.List;
/**
* @author Chen
* @version 1.0
* @date 2020/4/2 14:49
* @description:
*/
public class TestOK {
@Test
public void test7(){
// 使用动态代理技术虚拟调用方法
UserMapper userMapper = SqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectUserList("陈1", 20);
System.out.println(users);
}
}
控制台输出如下:
Console
使用动态代理技术拦截接口方法开始
拦截到ChenQueryList注解
java.lang.ClassCastException: java.lang.Object cannot be cast to java.util.List
at com.sun.proxy.$Proxy4.selectUserList(Unknown Source)
at com.njust.mybatisorm.TestOK.test7(TestOK.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Process finished with exit code -1
控制台成功输出我们的拦截信息。异常是因为我们还没有具体实现业务逻辑,这也是我们接下来要做的。至此,我们的业务环境已经搭建成功。
二、自定义代理完善
完善实际对数据库的增删改查功能。
1、JDBC工具类
定义JDBCUtils
类,封装JDBC
对数据库的操作,便于我们在拦截类中直接调用。这里为了简单起见,直接将数据库相关信息写死,读者可以将其配置到配置文件中。源码如下:
JDBCUtils .java
package com.njust.mybatisorm.utils;
import java.sql.*;
import java.util.List;
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/mysql_learning?useUnicode=true&characterEncoding=utf8";
/*
* 获取用户名
*/
username = "root";
/*
* 获取密码
*/
password = "root";
/*
* 设置是否自动提交,一般为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;
}
public static int delete(String SQL, List<Object> params) {
int var = -1;
if (SQL == null || SQL.trim().isEmpty()) {
throw new RuntimeException("你没有指定SQL语句,请检查是否指定了需要执行的SQL语句");
}
// 如果不是 insert 开头开头的语句
if (!SQL.trim().toLowerCase().startsWith("delete")) {
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, false);
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();
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);
var = count; // 如果不需要获得,则将受SQL影像的记录数赋值给 var 变量
commit(c); // 提交事务
} catch (SQLException e) {
System.out.println("数据删除失败: " + e.getMessage());
rollback(c); // 回滚事务
}
}
return var;
}
public static int update(String SQL, List<Object> params) {
int var = -1;
if (SQL == null || SQL.trim().isEmpty()) {
throw new RuntimeException("你没有指定SQL语句,请检查是否指定了需要执行的SQL语句");
}
// 如果不是 insert 开头开头的语句
if (!SQL.trim().toLowerCase().startsWith("update")) {
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, false);
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();
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);
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、SQL语句处理类
定义SQLUtils
类,封装Mybatis
语句到JDBC
语句的转化。由于mybatis
的底层是JDBC
,所以会出现Mybatis
语法和JDBC
语法的转换,所以我们将这些公共方法封装起来,便于拦截类调用。源码如下:
SQLUtils .java
package com.njust.mybatisorm.utils;
import java.util.ArrayList;
import java.util.List;
/**
* SQL拼接<br>
*/
public class SQLUtils {
/**
*
* 获取Insert语句后面values 参数信息<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语句
* @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;
}
public static String deal(StringBuilder sql) {
String result = null;
int start = sql.indexOf("#{");
int end = sql.indexOf("}");
result = sql.substring(start + 2, end);
return result;
}
/**
* 将SQL参数提取出来,并将最后生成的jdbc语句也放到list中
* @param sql
* @return
*/
public static List<String> dealList(String sql) {
StringBuilder stringBuilder = new StringBuilder(sql);
ArrayList<String> strings = new ArrayList<>();
while (stringBuilder.indexOf("#{") != -1) {
strings.add(deal(stringBuilder));
stringBuilder = stringBuilder.replace(stringBuilder.indexOf("#{"),
stringBuilder.indexOf("}") + 1, "?");
}
strings.add(String.valueOf(stringBuilder));
return strings;
}
public static String getTableName(String sql) {
sql = sql.toLowerCase();
String name = null;
int start = sql.indexOf("update");
int end = sql.indexOf("set");
name = sql.substring(start+6, end);
name = name.trim();
return name;
}
/**
* 将SQL语句的参数替换变为?<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;
}
}
3、完成拦截类
修改ChenInvocationHandlerMybatis
类,完成具体的业务逻辑处理。各个注解的处理流程类似,基本流程是首先判断方法上是否存在自定义注解。如果没有自定义注解则直接结束,否则获取注解上的SQL
语句。然后获取方法上的参数,将参数名称和参数值绑定在一起。
然后将mybatis
语法的SQL
语句替换成jdbc
的SQL
语句。接着调用jdbc
代码底层执行sql
语句。如果是基本类型则直接返回,如果是引用对象则使用反射机制实例对象,获取方法返回的类型,进行实例化返回给调用者。源码如下:
ChenInvocationHandlerMybatis .java
package com.njust.mybatisorm.orm.aop;
import com.njust.mybatisorm.orm.annotation.*;
import com.njust.mybatisorm.utils.JDBCUtils;
import com.njust.mybatisorm.utils.SQLUtils;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;
import java.lang.reflect.*;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import static com.njust.mybatisorm.utils.SQLUtils.getTableName;
/**
* 使用反射动态代理技术 拦截接口防范
*/
public class ChenInvocationHandlerMybatis implements InvocationHandler {
private Object object;
public ChenInvocationHandlerMybatis(Object object) {
this.object = object;
}
// proxy 代理对象 method拦截方法 args方法上的参数值
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("使用动态代理技术拦截接口方法开始");
// 使用白话问翻译,@ChenInsert封装过程
// 1. 判断方法上是否存在@ChenInsert
ChenInsert chenInsert = method.getDeclaredAnnotation(ChenInsert.class);
if (chenInsert != null) {
return chenInsert(chenInsert, proxy, method, args);
}
// 1. 判断方法上是否存 在删除注解
ChenDelete chenDelete = method.getDeclaredAnnotation(ChenDelete.class);
if (chenDelete != null) {
return chenDelete(chenDelete, proxy, method, args);
}
// 2.查询的思路
// 1. 判断方法上是否存 在查询注解
ChenQuery chenQuery = method.getDeclaredAnnotation(ChenQuery.class);
if (chenQuery != null) {
return chenQuery(chenQuery, proxy, method, args);
}
// 1. 判断方法上是否存 在查询注解
ChenQueryList chenQueryList = method.getDeclaredAnnotation(ChenQueryList.class);
if (chenQueryList != null) {
return chenQueryList(chenQueryList, proxy, method, args);
}
/**
* 更新
*/
ChenUpdate chenUpdate = method.getDeclaredAnnotation(ChenUpdate.class);
if (chenUpdate != null) {
return chenUpdate(chenUpdate, proxy, method, args);
}
/**
* 更新 返回更新数量
*/
ChenUpdateInt chenUpdateInt = method.getDeclaredAnnotation(ChenUpdateInt.class);
if (chenUpdateInt != null) {
return chenUpdateInt(chenUpdateInt, proxy, method, args);
}
return null;
}
private Object chenQuery(ChenQuery chenQuery, Object proxy, Method method, Object[] args)
throws SQLException, IllegalAccessException, InstantiationException {
// 2. 获取注解上查询的SQL语句
String selectSQL = chenQuery.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());
return getObject(method, newSql, sqlParams);
}
private List<Object> chenQueryList(ChenQueryList chenQueryList, Object proxy, Method method, Object[] args)
throws SQLException, IllegalAccessException, InstantiationException {
// 2. 获取注解上查询的SQL语句
String selectSQL = chenQueryList.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());
return getObjectList(method, newSql, sqlParams);
}
/**
* 5.调用jdbc代码底层执行sql语句
* 6.使用反射机制实例对象### 获取方法返回的类型,进行实例化
* 思路:
* 1.使用反射机制获取方法的类型
* 2.判断是否有结果集,如果有结果集,在进行初始化
* 3.使用反射机制,给对象赋值
*
* @param method
* @param newSql
* @param sqlParams
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
private Object getObject(Method method, String newSql, List<Object> sqlParams) throws SQLException, IllegalAccessException, InstantiationException {
ResultSet res = JDBCUtils.query(newSql, sqlParams);
// 判断是否存在值
if (!res.next()) {
return null;
}
// 下标往上移动移位
res.previous();
// 使用反射机制获取方法的类型
Class<?> returnType = method.getReturnType();
Object object = returnType.newInstance();
if (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);
}
}
return object;
}
private List<Object> getObjectList(Method method, String newSql, List<Object> sqlParams)
throws SQLException, IllegalAccessException, InstantiationException {
ResultSet res = JDBCUtils.query(newSql, sqlParams);
// 判断是否存在值
if (!res.next()) {
return null;
}
// 下标往上移动移位
res.previous();
// 使用反射机制获取方法的类型
Class<?> returnType = method.getReturnType();
// 获取泛型返回值
Type genericReturnType = method.getGenericReturnType();
// 获取list中泛型参数
Type[] actualTypeArguments = ((ParameterizedTypeImpl) genericReturnType).getActualTypeArguments();
ArrayList<Object> objects = new ArrayList<>();
while (res.next()) {
Object object = ((Class)actualTypeArguments[0]).newInstance();
// 获取当前所有的属性
Field[] declaredFields = ((Class)actualTypeArguments[0]).getDeclaredFields();
for (Field field : declaredFields) {
String fieldName = field.getName();
Object fieldValue = res.getObject(fieldName);
field.setAccessible(true);
field.set(object, fieldValue);
}
objects.add(object);
}
return objects;
}
private Object chenInsert(ChenInsert chenInsert, Object proxy, Method method, Object[] args) {
// 方法上存在@ChenInsert,获取他的SQL语句
// 2. 获取SQL语句,获取注解Insert语句
String insertSql = chenInsert.value();
// System.out.println("insertSql:" + insertSql);
// 3. 获取方法的参数和SQL参数进行匹配
// 定一个一个Map集合 KEY为@ChenParamValue,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 Object chenDelete(ChenDelete chenDelete, Object proxy, Method method, Object[] args) {
// 方法上存在@ChenInsert,获取他的SQL语句
// 2. 获取SQL语句,获取注解Insert语句
String deleteSql = chenDelete.value();
// System.out.println("insertSql:" + insertSql);
// 3. 获取方法的参数和SQL参数进行匹配
// 定一个一个Map集合 KEY为@ChenParamValue,Value 结果为参数值
ConcurrentHashMap<Object, Object> paramsMap = paramsMap(proxy, method, args);
// 4. 参数替换?传递方式
List<String> sqlSelectParameter = SQLUtils.dealList(deleteSql);
// 5.传递参数
List<Object> sqlParams = new ArrayList<>();
for (int i = 0; i < sqlSelectParameter.size() - 1; i++) {
Object parameterValue = paramsMap.get(sqlSelectParameter.get(i));
sqlParams.add(parameterValue);
}
// 4. 根据参数替换参数变为?
String newSQL = sqlSelectParameter.get(sqlSelectParameter.size() - 1);
System.out.println("newSQL:" + newSQL + ",sqlParams:" + sqlParams.toString());
// 5. 调用jdbc底层代码执行语句
return JDBCUtils.delete(newSQL, sqlParams);
}
private Object chenUpdate(ChenUpdate chenUpdate, Object proxy, Method method, Object[] args) throws IllegalAccessException, SQLException, InstantiationException {
// 方法上存在@ChenInsert,获取他的SQL语句
// 2. 获取SQL语句,获取注解Insert语句
String deleteSql = chenUpdate.value();
// System.out.println("insertSql:" + insertSql);
// 3. 获取方法的参数和SQL参数进行匹配
// 定一个一个Map集合 KEY为@ChenParamValue,Value 结果为参数值
ConcurrentHashMap<Object, Object> paramsMap = paramsMap(proxy, method, args);
// 4. 参数替换?传递方式
List<String> sqlSelectParameter = SQLUtils.dealList(deleteSql);
// 5.传递参数
List<Object> sqlParams = new ArrayList<>();
for (int i = 0; i < sqlSelectParameter.size() - 1; i++) {
Object parameterValue = paramsMap.get(sqlSelectParameter.get(i));
sqlParams.add(parameterValue);
}
// 4. 根据参数替换参数变为?
String newSQL = sqlSelectParameter.get(sqlSelectParameter.size() - 1);
System.out.println("newSQL:" + newSQL + ",sqlParams:" + sqlParams.toString());
// 5. 调用jdbc底层代码执行语句
JDBCUtils.update(newSQL, sqlParams);
newSQL = "select * from " + getTableName(newSQL) + " where id=?";
ArrayList<Object> objects = new ArrayList<>();
objects.add(paramsMap.get("id"));
return getObject(method, newSQL, objects);
}
private Object chenUpdateInt(ChenUpdateInt chenUpdateInt, Object proxy, Method method, Object[] args) throws IllegalAccessException, SQLException, InstantiationException {
// 方法上存在@ChenInsert,获取他的SQL语句
// 2. 获取SQL语句,获取注解Insert语句
String deleteSql = chenUpdateInt.value();
// System.out.println("insertSql:" + insertSql);
// 3. 获取方法的参数和SQL参数进行匹配
// 定一个一个Map集合 KEY为@ChenParamValue,Value 结果为参数值
ConcurrentHashMap<Object, Object> paramsMap = paramsMap(proxy, method, args);
// 4. 参数替换?传递方式
List<String> sqlSelectParameter = SQLUtils.dealList(deleteSql);
// 5.传递参数
List<Object> sqlParams = new ArrayList<>();
for (int i = 0; i < sqlSelectParameter.size() - 1; i++) {
Object parameterValue = paramsMap.get(sqlSelectParameter.get(i));
sqlParams.add(parameterValue);
}
// 4. 根据参数替换参数变为?
String newSQL = sqlSelectParameter.get(sqlSelectParameter.size() - 1);
System.out.println("newSQL:" + newSQL + ",sqlParams:" + sqlParams.toString());
// 5. 调用jdbc底层代码执行语句
return JDBCUtils.update(newSQL, 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];
ChenParam ChenParam = parameter.getDeclaredAnnotation(ChenParam.class);
if (ChenParam != null) {
// 参数名称
String paramName = ChenParam.value();
Object paramValue = args[i];
// System.out.println(paramName + "," + paramValue);
paramsMap.put(paramName, paramValue);
}
}
return paramsMap;
}
}
总结
概括
使用java动态代理拦截接口的调用,对不同注解分别处理对应的增删改查功能。
流程图
重点及易错点
1、返回值
代理方法的返回值一定要和接口一致,尤其是多结果的List类型,这里不能直接使用放射的返回结果创建实例,而是要取得泛型类型,在对对象一个个的属性赋值,手动添加到容器中再返回。
2、res.next()
使用res.next()
判断是否存在值后,如果存在在一定要调用res.previous();
方法进行回滚。因为我们调用res.next()
函数判断的时候指针已经向后移动了。
有问题欢迎各位读者批评指正。
点个赞再走呗!欢迎留言哦!