本文實現的功能其實是圍繞 mybatis中的@insert(插入)和@select(查詢)和@param(參數綁定)來的。
其中主要目標是獲取註解中的sql語句,並拼接成可執行的語句。
難點在於由於使用的是接口不能利用反射技術獲取註解中的值,而是要使用動態代理技術(字節碼)。
1. 倚賴
添加好驅動即可
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
- 自定義註解
/**
* 自定義insert
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtInsert {
String value();
}
// 查詢註解
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtSelect {
String value();
}
@Target(value = { ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtParam {
String value();
}
- 編寫代理類:
/**
* 功能說明:手寫mybatis框架註解版本
* 1.使用動態代理技術,獲取接口方法上的sql語句
* 2.根據不同的SQL語句
*/
public class MyInvocationHandlerMbatis implements InvocationHandler {
/**
* 這個就是我們要代理的真實對象
*/
private Object subject;
/**
* 構造方法,給我們要代理的真實對象賦初值
*
* @param subject
*/
public MyInvocationHandlerMbatis(Object subject) {
this.subject = subject;
}
/**
* 該方法負責集中處理動態代理類上的所有方法調用。 調用處理器根據這三個參數進行預處理或分派到委託類實例上反射執行
*
* @param proxy
* 代理類實例
* @param method
* 被調用的方法對象
* @param args
* 調用參數
* @return
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 判斷方法上是否有ExtInsert註解
ExtInsert extInsert = method.getAnnotation(ExtInsert.class);
if (extInsert != null) {
return insertSQL(extInsert, method, args);
}
// 判斷方法上註解類型
ExtSelect extSelect = method.getAnnotation(ExtSelect.class);
if (extSelect != null) {
return selectMybatis(extSelect, method, args);
}
return null;
}
public int insertSQL(ExtInsert extInsert, Method method, Object[] args) {
// 獲取註解上的sql
String insertSql = extInsert.value();
System.out.println("sql:" + insertSql);
// 獲取方法上的參數
Parameter[] parameters = method.getParameters();
// 將方法上的參數存放在Map集合中
ConcurrentHashMap<Object, Object> parameterMap = getExtParams(parameters, args);
// 獲取SQL語句上需要傳遞的參數
String[] sqlParameter = SQLUtils.sqlInsertParameter(insertSql);
List<Object> parameValues = new ArrayList<>();
for (int i = 0; i < sqlParameter.length; i++) {
String str = sqlParameter[i];
Object object = parameterMap.get(str);
parameValues.add(object);
}
// 將SQL語句替換爲?號
String newSql = SQLUtils.parameQuestion(insertSql, sqlParameter);
System.out.println("newSql:" + newSql);
// 調用jdbc代碼執行
int insertResult = JDBCUtils.insert(newSql, false, parameValues);
return insertResult;
}
public Object selectMybatis(ExtSelect extInsert, Method method, Object[] args) throws SQLException {
try {
// 獲取查詢SQL語句
String selectSQL = extInsert.value();
// 將方法上的參數存放在Map集合中
Parameter[] parameters = method.getParameters();
// 獲取方法上參數集合
ConcurrentHashMap<Object, Object> parameterMap = getExtParams(parameters, args);
// 獲取SQL傳遞參數
List<String> sqlSelectParameter = SQLUtils.sqlSelectParameter(selectSQL);
// 排序參數
List<Object> parameValues = new ArrayList<>();
for (int i = 0; i < sqlSelectParameter.size(); i++) {
String parameterName = sqlSelectParameter.get(i);
Object object = parameterMap.get(parameterName);
parameValues.add(object.toString());
}
// 變爲?號
String newSql = SQLUtils.parameQuestion(selectSQL, sqlSelectParameter);
System.out.println("執行SQL:" + newSql + "參數信息:" + parameValues.toString());
// 調用JDBC代碼查詢
ResultSet rs = JDBCUtils.query(newSql, parameValues);
// 獲取返回類型
Class<?> returnType = method.getReturnType();
if (!rs.next()) {
// 沒有查找數據
return null;
}
// 向上移動
rs.previous();
// 實例化對象
Object newInstance = returnType.newInstance();
while (rs.next()) {
for (String parameterName : sqlSelectParameter) {
// 獲取集合中數據
Object value = rs.getObject(parameterName);
// 查找對應屬性
Field field = returnType.getDeclaredField(parameterName);
// 設置允許私有訪問
field.setAccessible(true);
// 賦值參數
field.set(newInstance, value);
}
}
return newInstance;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private ConcurrentHashMap<Object, Object> getExtParams(Parameter[] parameters, Object[] args) {
// 獲取方法上參數集合
ConcurrentHashMap<Object, Object> parameterMap = new ConcurrentHashMap<>();
for (int i = 0; i < parameters.length; i++) {
// 參數信息
Parameter parameter = parameters[i];
ExtParam extParam = parameter.getDeclaredAnnotation(ExtParam.class);
// 參數名稱
String paramValue = extParam.value();
// 參數值
Object oj = args[i];
parameterMap.put(paramValue, oj);
}
return parameterMap;
}
}
- 工具類:
/**
* SQL拼接
*/
public class SQLUtils {
/**
*
* 獲取Insert語句後面values 參數信息
* @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;
}
/**
* @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語句的參數替換變爲?
*
*
* @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 sql = "insert into user(userName,userAge)
// values(#{userName},#{userAge})";
// String[] sqlParameter = sqlInsertParameter(sql);
// for (String string : sqlParameter) {
// System.out.println(string);
// }
List<String> sqlSelectParameter = SQLUtils
.sqlSelectParameter("select * from User where userName=#{userName} and userAge=#{userAge} ");
for (String string : sqlSelectParameter) {
System.out.println(string);
}
}
}
JDBCUtils:
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 = "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;
}
/** 提交事務 */
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();
}
}
}
}
}
- SqlSession
/**
* 獲取SqlSession對象
*/
public class SqlSession {
// 獲取getMapper
public static <T> T getMapper(Class<T> clas)
throws IllegalArgumentException, InstantiationException, IllegalAccessException {
return (T) Proxy.newProxyInstance(clas.getClassLoader(), new Class[] { clas },
new MyInvocationHandlerMbatis(clas));
}
}
- 測試
public class Test01 {
public static void main(String[] args)
throws IllegalArgumentException, InstantiationException, IllegalAccessException {
UserDao mapper = SqlSession.getMapper(UserDao.class);
int insertUser = mapper.insertUser(18, "洺潤Star");
System.out.println("影響行數:" + insertUser);
User user = mapper.selectUser("111", 111);
System.out.println("查詢結果:" + user.getUserName() + "," +
user.getUserAge());
}
}
成功搞定