1.首先是用到的两个工具类:
package com.wangyu.utils;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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/rbac_db?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
2.自定义的注解和sqlsession
//添加
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ExtInsert {
String value();
}
//参数
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface ExtParam {
String value();
}
//查询
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ExtSelect {
String value();
}
///
public class SqlSession {
public static T getMapper(Class classz) {
return (T)Proxy.newProxyInstance(classz.getClassLoader(), new Class[]{classz}, new MyInvocationHandlerMbatis(classz));
}
}
3.最重要的aop拦截
package com.wangyu.aop;
import com.wangyu.annotation.ExtInsert;
import com.wangyu.annotation.ExtParam;
import com.wangyu.annotation.ExtSelect;
import com.wangyu.utils.JDBCUtils;
import com.wangyu.utils.SQLUtils;
import org.apache.ibatis.binding.MapperMethod;
import java.lang.reflect.*;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import static javax.xml.soap.SOAPFactory.newInstance;
/**
* 类说明此demo只是实现了添加和查询,且查询还需改造方可用于实战(返回类型)
*
* @author wangyu
* @version 1.0
* @date $2018/11/20$ $15:35$
*/
public class MyInvocationHandlerMbatis implements InvocationHandler {
public Object obj;
public MyInvocationHandlerMbatis(Object obj) {
this.obj = obj;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("使用动态代理拦截dao接口---");
ExtInsert extInsert = method.getDeclaredAnnotation(ExtInsert.class);
//1.判断方法是否加了insert注解
if (extInsert != null) {
return extInsert(extInsert, method, args);
}
ExtSelect extSelect = method.getDeclaredAnnotation(ExtSelect.class);
//2.查询
if (extSelect != null) {
//注解存在获取sql
String querySql = extSelect.value();
//获取参数绑定
ConcurrentHashMap paramMap = getConcurrentHashMap(method, args);
List sqlSelectParameter = SQLUtils.sqlSelectParameter(querySql);
List sqlParam = new ArrayList();
for (String string : sqlSelectParameter) {
Object paramValue = paramMap.get(string);
sqlParam.add(paramValue);
}
String newSql = SQLUtils.parameQuestion(querySql, sqlSelectParameter);
//调用jdbc
ResultSet resultSet = JDBCUtils.query(newSql, sqlParam);
if (!resultSet.next()) {
return null;
}
resultSet.previous();//下标上移一位
Class> returnType = method.getReturnType();
Type type = method.getReturnType();
System.out.println("returnType:"+returnType);
Object object = returnType.newInstance();
while (resultSet.next()) {
//反射机制获取实例化对象
Field[] declaredFields = returnType.getDeclaredFields();
for (Field field : declaredFields) {
String fieldName = field.getName();
Object filedValue = resultSet.getObject(fieldName);
field.setAccessible(true);//设置私有属性可以访问
field.set(object, filedValue);
}
/* for (String paramName : sqlSelectParameter) {
Object resultValue = resultSet.getObject(paramName);
Field field = returnType.getDeclaredField(paramName);
field.setAccessible(true);
field.set(object, resultValue);
}*/
}
return object;
}
return null;
}
//insert
private Object extInsert(ExtInsert extInsert, Method method, Object[] args) {
//2.存在注解,获取sql 截取sql
String insertSql = extInsert.value();
System.out.println("insertSql:" + insertSql);
//3.获取参数 定义map集合接收参数
ConcurrentHashMap paramMap = getConcurrentHashMap(method, args);
//4.替换参数 ?
String[] sqlInsertParameter = SQLUtils.sqlInsertParameter(insertSql);
List sqlParams = getSqlParam(sqlInsertParameter, paramMap);
String newSql = SQLUtils.parameQuestion(insertSql, sqlInsertParameter);
System.out.println("拼接后的sql:" + newSql + ",参数有:" + sqlParams.toString());
//5.调用jdbc
JDBCUtils.insert(newSql, false, sqlParams);
return 1;
}
//获取方法的参数
private ConcurrentHashMap getConcurrentHashMap(Method method, Object[] args) {
ConcurrentHashMap paramMap = new ConcurrentHashMap<>();
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameters.length; i++) {
Parameter parameter = parameters[i];
ExtParam extParam = parameter.getAnnotation(ExtParam.class);
if (extParam != null) {
String paramName = extParam.value();
Object paramValue = args[i];
System.out.println(paramName + "---" + paramValue);
/* if(extParam.value()==parameter.getName()){}*/
paramMap.put(paramName, paramValue);
}
}
return paramMap;
}
//替换参数
private List getSqlParam(String[] sqlInsertParameter, ConcurrentHashMap paramMap) {
List sqlParams = new ArrayList<>();
for (String paramName : sqlInsertParameter) {
Object paramValue = paramMap.get(paramName);
sqlParams.add(paramValue);
}
return sqlParams;
}
}
4.接口和实体类
public interface UserMapper {
/* @Insert(value = "insert into rbac_db.user (name, age)values(#{name}, #{age)")
void addUser(User user);*/
@ExtInsert(value = "insert into rbac_db.user (name, age)values(#{name},#{age})")
int addUser(@ExtParam("name") String name, @ExtParam("age") int age);
@ExtSelect("select * from rbac_db.user where name=#{name}")
User query(@ExtParam("name") String name);
}
//
package com.wangyu.entity;
/**
* 类说明
*
* @author wangyu
* @version 1.0
* @date $2018/11/20$ $14:52$
*/
public class User {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
5.测试
package com.wangyu;
import com.wangyu.SqlSeeion.SqlSession;
import com.wangyu.aop.MyInvocationHandlerMbatis;
import com.wangyu.entity.User;
import com.wangyu.mapper.UserMapper;
import java.util.List;
/**
* 类说明
*
* @author wangyu
* @version 1.0
* @date $2018/11/20$ $15:10$
*/
public class Test001 {
public static void main(String[] args) {
UserMapper userMapper = SqlSession.getMapper(UserMapper.class);
// int addResult = userMapper.addUser("A2", 12);
User user = userMapper.query("项羽");
System.out.println(user.getAge() + "----" + user.getName());
//System.out.println(list);
}
}