1.MyBatis簡介
MyBatis是一個ORM工具,封裝了JDBC的操作,簡化業務編程;
Mybatis在web工程中,與Spring集成,提供業務讀寫數據庫的能力。
2.使用步驟 1.引入依賴
采用Maven包依賴管理,mybatis-3.5.5版本;同時需要數據庫連接驅動
org.mybatis mybatis 3.5.5 MySQL mysql-connector-JAVA 5.1.49
2.配置文件
配置文件配置數據庫連接源,及映射文件。
DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> root" />
3.接口定義
定義實體
package com.xiongxin.mybatis.entity; public class User { private String username; private String password; ...getter&&setter }
接口定義
package com.xiongxin.mybatis.mApper; import com.xiongxin.mybatis.entity.User; import java.util.List; public interface UserMapper { List queryUser(); }
定義映射文件
select * from tbl_user
4.加載執行 package com.xiongxin.mybatis; import com.alibaba.fastjson.JSON; import com.xiongxin.mybatis.entity.User; import com.xiongxin.mybatis.mapper.UserMapper; import org.Apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.sqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.IOException; import java.io.Reader; import java.util.List; public class TestMain { public static void main(String[] args) throws IOException { String resource = "mybatis-config.xml"; //加載 mybatis 的配置文件(它也加載關聯的映射文件) Reader reader = Resources.getResourceAsReader(resource); //構建 SqlSession 的工廠 SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader); //創建能執行映射文件中 sql 的 sqlSession SqlSession session = sessionFactory.openSession(); UserMapper userMapper = session.getMapper(UserMapper.class); List users = userMapper.queryUser(); System.out.println(JSON.toJSONString(users)); } } --------------------------------- ..consule print.. [{"password":"password","username":"xiongxin"}]
到這里,這個Mybatis的使用環節結束。
整個實現過程中,我們并未編寫Mapper的實現類,框架是如何在無實現類的場景下實現接口方法返回的呢?
這里就不得不說到接口的動態代理方法了。
3.原理解析
SqlSession接口的實現中,獲取Mapper的代理實現類
使用了JDK動態代理的功能
代理類執行方法調用
方法調用中執行MethodInvoker
最終執行execue方法。
獲取返回結果Result
4.手撕框架
前置知識:
源碼:
牛逼??!接私活必備的 N 個開源項目!趕快收藏
com.alibaba fastjson 1.2.74 com.h2database h2 1.4.199
package com.dbutil.session; import java.lang.Annotation.Retention; import java.lang.annotation.Target; import java.lang.reflect.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import static java.lang.annotation.ElementType.*; import static java.lang.annotation.RetentionPolicy.RUNTIME; /** * @author xiongxin */ public class SqlSession { public static Connection getConnH2() throws Exception { String url = "jdbc:h2:mem:db_h2;MODE=MYSQL;INIT=RUNSCRIPT FROM './src/main/resources/schema.sql'"; String user = "root"; String password = "123456"; //1.加載驅動程序 Class.forName("org.h2.Driver"); //2.獲得數據庫鏈接 Connection conn = DriverManager.getConnection(url, user, password); Return conn; } /** * 自定義注解 */ @Target({TYPE, FIELD, METHOD}) @Retention(RUNTIME) public @interface QueryList { public String value(); } /** * 動態代理 * * @param mapperInterface * @param * @return */ public static T getMapper(Class mapperInterface) { return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{mapperInterface}, new MapperInvocationHandler()); } /** * 代理類方法 */ public static class MapperInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String sql = method.getAnnotation(QueryList.class).value(); Class returnType = method.getReturnType(); //返回類型為List if (returnType == List.class) { Type genericReturnType = method.getGenericReturnType(); String TypeName = genericReturnType.getTypeName(); String replace = typeName.replace("java.util.List<", "").replace(">", ""); //獲取泛型類型 Class forName = Class.forName(replace); return SqlSession.queryList(sql, forName); } return null; } } /** * 結果集轉換 * * @param */ public interface ResultMap { T convert(ResultSet resultSet) throws Exception; } /** * 創建連接并執行 * * @param sql * @param resultMap * @param * @return * @throws Exception */ public static List queryList(String sql, ResultMap resultMap) throws Exception { //jdbc數據庫 Connection conn = getConnH2(); //3.通過數據庫的連接操作數據庫,實現增刪改查(使用Statement類) Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql); List list = new ArrayList<>(); //4.處理數據庫的返回結果(使用ResultSet類) while (rs.next()) { T convert = resultMap.convert(rs); list.add(convert); } //關閉資源 rs.close(); st.close(); conn.close(); return list; } /** * 查詢數據集 * * @param sql * @param returnType * @param * @return * @throws Exception */ public static List queryList(String sql, Class returnType) throws Exception { List list = SqlSession.queryList(sql, rs -> { T obj = returnType.newInstance(); Field[] declaredFields = returnType.getDeclaredFields(); for (Field declaredField : declaredFields) { Class type = declaredField.getType(); //類型為String時的處理方法 if (type == String.class) { String value = rs.getString(declaredField.getName()); String fieldName = declaredField.getName(); Method method = returnType.getDeclaredMethod( "set".concat(fieldName.substring(0, 1).toUpperCase().concat(fieldName.substring(1))), String.class); method.invoke(obj, value); } if (type == Long.class) { Long value = rs.getLong(declaredField.getName()); String fieldName = declaredField.getName(); Method method = returnType.getDeclaredMethod( "set".concat(fieldName.substring(0, 1).toUpperCase().concat(fieldName.substring(1))), Long.class); method.invoke(obj, value); } //其他類型處理方法 } return obj; }); return list; } }
schema.sql文件
drop table if exists user; CREATE TABLE user ( id int(11) NOT NULL AUTO_INCREMENT, username varchar(255) DEFAULT NULL, password varchar(255) DEFAULT NULL, PRIMARY KEY (id) ); insert into user(id,username,password) values(1,'xiongxina','123456'); insert into user(id,username,password) values(2,'xiongxinb','123456'); insert into user(id,username,password) values(3,'xiongxinc','123456');
mapper定義
package com.dbutil.mapper; import com.dbutil.entity.UserEntity; import com.dbutil.session.SqlSession; import java.util.List; public interface UserMapper { @SqlSession.QueryList("select * from user") List queryUser(); }
使用:
package com.dbutil; import com.dbutil.entity.UserEntity; import com.dbutil.mapper.UserMapper; import com.dbutil.session.SqlSession; import java.util.List; public class UserService { public static void main(String[] args) throws Exception { UserMapper userMapper = SqlSession.getMapper(UserMapper.class); List userEntities = userMapper.queryUser(); for (UserEntity userEntity : userEntities) { System.out.println(userEntity); } } }
原文鏈接:https://mp.weixin.qq.com/s/E00PkxeKrY9ZttPWh69t5G