更新時(shí)間:2022-10-17 來(lái)源:黑馬程序員 瀏覽量:
1. 自定義MyBatis框架流程分析
2. 自定義框架原理介紹
3. 準(zhǔn)備工作:
1) 創(chuàng)建maven工程
Groupid:com.itheima ArtifactId:custom-mybatis Packing:jar
2) 添加pom依賴:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.15</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.12</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1</version> </dependency> <dependency> <groupId>jaxen</groupId> <artifactId>jaxen</artifactId> <version>1.1.6</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.12</version> </dependency>
4. 自定義MyBatis框架的實(shí)現(xiàn)步驟
需要定義的類的分析:
1.加載類加載目錄下的資源文件 `Resources.java`
2. 映射文件解析后信息類 `Mapper.java`
3. 保存配置文件的配置信息 `Configuration.java`
4. 配置文件解析的工具類`XMLConfigBuilder.java`
5. SQL語(yǔ)句的執(zhí)行對(duì)象`Executor.java`
6. 獲取數(shù)據(jù)源的工具類`JdbcUtil.java`
7. `SqlSession`接口及實(shí)現(xiàn)類
8. `SqlSessionFactory`接口及實(shí)現(xiàn)類
9. `SqlSessionFactory`的構(gòu)建者類`SqlSessionFactoryBuilder.java`
10. 動(dòng)態(tài)代理的處理類`MapperProxyFactory.java`
兩大步:
> 1-4 : 是我們前面提到的 解析xml,封裝對(duì)象;
>
> 5-10: 是得到sqlsession,獲取代理對(duì)象,執(zhí)行sql的核心代碼;
包結(jié)構(gòu)參考:
1)定義加載資源類`Resources.java`
/** * 加載資源的工具類 */ public class Resources { /** * 加載類加載目錄下的資源 * @param path * @return */ public static InputStream getResourceAsStream(String path){ return Resources.class.getClassLoader().getResourceAsStream(path); } }
2)定義mybatis映射配置信息類 `Mapper.java`
/** * 映射的配置信息類 */ @Data public class Mapper { private String queryString;// SQL語(yǔ)句 private String resultType;// 實(shí)體類全限定名 }
3)定義mybatis核心配置信息類 `Configuration.java`
/** * mybatis配置的實(shí)體類 * 用來(lái)保存mybatis.xml解析過(guò)程中的節(jié)點(diǎn)屬性 */ @Data public class Configuration { private String driver; //jdbc驅(qū)動(dòng)類 private String url; //jdbc連接字符串 private String username; //數(shù)據(jù)庫(kù)連接用戶名 private String password; //數(shù)據(jù)庫(kù)連接密碼 private Map<String, Mapper> mappers = new HashMap<String, Mapper>();//映射文件 public void setMappers(Map<String, Mapper> mappers) { this.mappers.putAll(mappers);//此處需要使用追加的方式 } }
4)配置文件解析的工具類`XMLConfigBuilder`
/** * 用于解析配置文件: * sqlmapconfig.xml * xxxMapper.xml */ public class XMLConfigBuilder { //定義封裝連接信息的配置對(duì)象(mybatis的配置對(duì)象) private static Configuration cfg = new Configuration(); /** * 解析主配置文件,把里面的內(nèi)容填充到DefaultSqlSession所需要的地方 * 使用的技術(shù):dom4j+xpath */ public static Configuration loadConfiguration(InputStream config){ try{ //1.獲取SAXReader對(duì)象 SAXReader reader = new SAXReader(); //2.根據(jù)字節(jié)輸入流獲取Document對(duì)象 Document document = reader.read(config); //3.獲取根節(jié)點(diǎn) Element root = document.getRootElement(); //4. 解析數(shù)據(jù)源信息 loadDataSourceElement(root); //5. 加載mapper loadMapperElement(root); //6. 返回Configuration return cfg; }catch(Exception e){ throw new RuntimeException(e); }finally{ try { config.close(); }catch(Exception e){ e.printStackTrace(); } } } /** * 解析數(shù)據(jù)源信息 */ public static void loadDataSourceElement(Element root) { //1.使用xpath中選擇指定節(jié)點(diǎn)的方式,獲取所有property節(jié)點(diǎn) List<Element> propertyElements = root.selectNodes("//property"); //2.遍歷節(jié)點(diǎn) for(Element propertyElement : propertyElements){ //判斷節(jié)點(diǎn)是連接數(shù)據(jù)庫(kù)的哪部分信息 //取出name屬性的值 String name = propertyElement.attributeValue("name"); if("driver".equals(name)){ //表示驅(qū)動(dòng) //獲取property標(biāo)簽value屬性的值 String driver = propertyElement.attributeValue("value"); cfg.setDriver(driver); } if("url".equals(name)){ //表示連接字符串 //獲取property標(biāo)簽value屬性的值 String url = propertyElement.attributeValue("value"); cfg.setUrl(url); } if("username".equals(name)){ //表示用戶名 //獲取property標(biāo)簽value屬性的值 String username = propertyElement.attributeValue("value"); cfg.setUsername(username); } if("password".equals(name)){ //表示密碼 //獲取property標(biāo)簽value屬性的值 String password = propertyElement.attributeValue("value"); cfg.setPassword(password); } } } /** * 加載mapper */ public static void loadMapperElement(Element root) throws Exception { //取出mappers中的所有mapper標(biāo)簽,判斷他們使用了resource還是class屬性 List<Element> mapperElements = root.selectNodes("//mappers/mapper"); //遍歷集合 for(Element mapperElement : mapperElements){ //判斷mapperElement使用的是哪個(gè)屬性 Attribute attribute = mapperElement.attribute("resource"); if(attribute != null){ System.out.println("------XML方式mapper----"); //表示有resource屬性,用的是XML //取出屬性的值 String mapperPath = attribute.getValue();//獲取屬性的值"com/itheima/dao/IUserDao.xml" //把映射配置文件的內(nèi)容獲取出來(lái),封裝成一個(gè)map Map<String,Mapper> mappers = loadMapperConfiguration(mapperPath); //給configuration中的mappers賦值 cfg.setMappers(mappers); } } } /** * 根據(jù)傳入的參數(shù),解析XML,并且封裝到Map中 * @param mapperPath 映射配置文件的位置 * @return map中包含了獲取的唯一標(biāo)識(shí)(key是由dao的全限定類名和方法名組成) * 以及執(zhí)行所需的必要信息(value是一個(gè)Mapper對(duì)象,里面存放的是執(zhí)行的SQL語(yǔ)句和要封裝的實(shí)體類全限定類名) */ private static Map<String,Mapper> loadMapperConfiguration(String mapperPath)throws IOException { InputStream in = null; try{ //定義返回值對(duì)象 Map<String,Mapper> mappers = new HashMap<String,Mapper>(); //1.根據(jù)路徑獲取字節(jié)輸入流 in = Resources.getResourceAsStream(mapperPath); //2.根據(jù)字節(jié)輸入流獲取Document對(duì)象 SAXReader reader = new SAXReader(); Document document = reader.read(in); //3.獲取根節(jié)點(diǎn) Element root = document.getRootElement(); //4.獲取根節(jié)點(diǎn)的namespace屬性取值 String namespace = root.attributeValue("namespace");//是組成map中key的部分 //5.獲取所有的select節(jié)點(diǎn) List<Element> selectElements = root.selectNodes("//select"); //6.遍歷select節(jié)點(diǎn)集合 for(Element selectElement : selectElements){ //取出id屬性的值 組成map中key的部分 String id = selectElement.attributeValue("id"); //取出resultType屬性的值 組成map中value的部分 String resultType = selectElement.attributeValue("resultType"); //取出文本內(nèi)容 組成map中value的部分 String queryString = selectElement.getText(); //創(chuàng)建Key String key = namespace+"."+id; //創(chuàng)建Value Mapper mapper = new Mapper(); mapper.setQueryString(queryString); mapper.setResultType(resultType); //把key和value存入mappers中 mappers.put(key,mapper); } return mappers; }catch(Exception e){ throw new RuntimeException(e); }finally{ in.close(); } } }
5)SQL語(yǔ)句的執(zhí)行對(duì)象`Executor.java`
/** * 負(fù)責(zé)執(zhí)行SQL語(yǔ)句,并且封裝結(jié)果集 */ public class Executor { /** * 根據(jù)mapper查詢多條數(shù)據(jù) * @param mapper * @param conn * @param <E> * @return */ public <E> List<E> selectList(Mapper mapper, Connection conn) { PreparedStatement pstm = null; ResultSet rs = null; try { //1.取出mapper中的數(shù)據(jù) String queryString = mapper.getQueryString();//select * from user String resultType = mapper.getResultType();//com.itheima.domain.User Class domainClass = Class.forName(resultType); //2.獲取PreparedStatement對(duì)象 pstm = conn.prepareStatement(queryString); //3.執(zhí)行SQL語(yǔ)句,獲取結(jié)果集 rs = pstm.executeQuery(); //4.封裝結(jié)果集 List<E> list = new ArrayList<E>();//定義返回值 while (rs.next()) { //將結(jié)果集中的數(shù)據(jù)封裝到實(shí)體中 E obj = extraction(rs, domainClass); //把賦好值的對(duì)象加入到集合中 list.add(obj); } return list; } catch (Exception e) { throw new RuntimeException(e); } finally { release(conn, pstm, rs); } } /** * 根據(jù)mapper查詢數(shù)據(jù),查詢一條數(shù)據(jù),如果結(jié)果集中有多條數(shù)據(jù),返回第一條數(shù)據(jù)封裝的實(shí)體對(duì)象 * @param mapper * @param conn * @param <E> * @return */ public <E> E selectOne(Mapper mapper, Connection conn) { PreparedStatement pstm = null; ResultSet rs = null; try { //1.取出mapper中的數(shù)據(jù) String queryString = mapper.getQueryString();//select * from user where id = ? String resultType = mapper.getResultType();//com.itheima.domain.User Class domainClass = Class.forName(resultType); //2.獲取PreparedStatement對(duì)象 pstm = conn.prepareStatement(queryString); //3.執(zhí)行SQL語(yǔ)句,獲取結(jié)果集 rs = pstm.executeQuery(); //4.封裝結(jié)果集 if (rs.next()) { //將結(jié)果集中的數(shù)據(jù)封裝到實(shí)體中 E obj = extraction(rs, domainClass); return obj; } return null; } catch (Exception e) { throw new RuntimeException(e); } finally { release(conn, pstm, rs); } } /** * 將結(jié)果集中的一條數(shù)據(jù)封裝到實(shí)體對(duì)象中 * @param rs * @param domainClass * @param <E> * @return * @throws Exception */ private <E> E extraction(ResultSet rs,Class domainClass) throws Exception{ //實(shí)例化要封裝的實(shí)體類對(duì)象 E obj = (E) domainClass.newInstance(); //取出結(jié)果集的元信息:ResultSetMetaData ResultSetMetaData rsmd = rs.getMetaData(); //取出總列數(shù) int columnCount = rsmd.getColumnCount(); //遍歷總列數(shù) for (int i = 1; i <= columnCount; i++) { //獲取每列的名稱,列名的序號(hào)是從1開始的 String columnName = rsmd.getColumnName(i); //根據(jù)得到列名,獲取每列的值 Object columnValue = rs.getObject(columnName); //給obj賦值:使用Java內(nèi)省機(jī)制(借助PropertyDescriptor實(shí)現(xiàn)屬性的封裝) PropertyDescriptor pd = new PropertyDescriptor(columnName, domainClass);//要求:實(shí)體類的屬性和數(shù)據(jù)庫(kù)表的列名保持一種 //獲取它的寫入方法 Method writeMethod = pd.getWriteMethod(); //把獲取的列的值,給對(duì)象賦值 writeMethod.invoke(obj, columnValue); } return obj; } private void release(Connection conn, PreparedStatement pstm, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } if (pstm != null) { try { pstm.close(); } catch (Exception e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } }
6)編寫獲取數(shù)據(jù)源的工具類`JdbcUtil`
/** * 用于創(chuàng)建數(shù)據(jù)源的工具類 */ public class JdbcUtil { /** * 用于獲取一個(gè)連接 * @param cfg * @return */ public static Connection getConnection(Configuration cfg){ try { Class.forName(cfg.getDriver()); return DriverManager.getConnection(cfg.getUrl(), cfg.getUsername(), cfg.getPassword()); }catch(Exception e){ throw new RuntimeException(e); } } }
7) 定義SqlSession的接口及實(shí)現(xiàn)類
接口`SqlSession.java`
public interface SqlSession { /** * 獲取mapper代理對(duì)象 * @param clzz * @param <T> * @return */ <T> T getMapper(Class<T> clzz) ; /** * 釋放資源 */ void close(); }
實(shí)現(xiàn)類`DefaultSqlSession.java`
public class DefaultSqlSession implements SqlSession { private Connection connection; private Map<String, Mapper> mappers; /** * 創(chuàng)建SqlSession對(duì)象時(shí),初始化執(zhí)行器對(duì)象 * @param mappers * @param connection */ public DefaultSqlSession(Map<String, Mapper> mappers, Connection connection) { this.mappers = mappers ; this.connection = connection ; } /** * 獲取持久層對(duì)象的代理對(duì)象 * * @param clzz * @param <T> * @return */ public <T> T getMapper(Class<T> clzz) { return (T) Proxy.newProxyInstance(clzz.getClassLoader(), new Class[]{clzz}, new MapperProxyFactory(connection,mappers)); } @Override public void close() { if(connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
8) 編寫動(dòng)態(tài)代理的處理類`MapperProxyFactory.java`
/** * 創(chuàng)建代理對(duì)象的InvocationHandler的實(shí)現(xiàn)類 */ public class MapperProxyFactory implements InvocationHandler { private Connection connection; private Map<String, Mapper> mappers; public MapperProxyFactory(Connection connection, Map<String, Mapper> mappers) { this.connection = connection ; this.mappers = mappers ; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { //1. 獲取需要執(zhí)行的sql語(yǔ)句 //1.1 獲取執(zhí)行的方法名稱----需要根據(jù)方法名稱找到對(duì)應(yīng)的需要執(zhí)行的sql語(yǔ)句 String methodName = method.getName(); //1.2 獲取方法所在類的全路徑名稱 String className = method.getDeclaringClass().getName(); //1.3 獲取需要執(zhí)行的statement String statment = className+"."+methodName; //1.4 獲取返回值類型 Class<?> type = method.getReturnType(); //1.5 根據(jù)查詢結(jié)果調(diào)用查詢方法 if(type == List.class){ return new Executor().selectList(mappers.get(statment),connection); } if(type != List.class){ return new Executor().selectOne(mappers.get(statment),connection); } return method.invoke(new Object(),args) ; } }
9) 創(chuàng)建SqlSessionFactory的接口及實(shí)現(xiàn)類
接口`SqlSessionFactory.java`
/** * SqlSession工廠 */ public interface SqlSessionFactory { /** * 創(chuàng)建session * @return */ public SqlSession openSession(); }
實(shí)現(xiàn)類`DefaultSqlSessionFactory.java`
/** * SqlSession工廠的實(shí)現(xiàn)類 */ public class DefaultSqlSessionFactory implements SqlSessionFactory { /** * 配置文件的輸入流 */ private Configuration configuration; public DefaultSqlSessionFactory(Configuration configuration){ this.configuration = configuration; } /** * 創(chuàng)建sqlSession * @return */ public SqlSession openSession() { DefaultSqlSession sqlSession = new DefaultSqlSession(configuration.getMappers(), JdbcUtil.getConnection(configuration)); return sqlSession; } }
10)定義SqlSession工廠的構(gòu)建者類
/** * SqlSession工廠的構(gòu)建者 */ public class SqlSessionFactoryBuilder { /** * 構(gòu)建session工廠 * @param is * @return */ public SqlSessionFactory build(InputStream is){ Configuration configuration = XMLConfigBuilder.loadConfiguration(is); DefaultSqlSessionFactory factory = new DefaultSqlSessionFactory(configuration); return factory; } }
11) 把自定義的mybatis打成jar:install
12) 測(cè)試自定義框架
```
創(chuàng)建maven測(cè)試工程
引入依賴
打成jar文件的自定義MyBatis框架
mysql驅(qū)動(dòng)
junit測(cè)試
引入配置文件:自定義mybatis一樣,將resource中的文件復(fù)制一份
創(chuàng)建User實(shí)體類
```
> 需求:
> 之前導(dǎo)入mybatis依賴能運(yùn)行的項(xiàng)目,去掉mybatis,引入我們自定義的這個(gè)jar的依賴,如果能夠成功運(yùn)行,就代表自定義框架是OK的!
測(cè)試代碼:
/** * 測(cè)試代碼 */ public static void main(String[] args)throws Exception { //1.讀取配置文件 InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); //2.創(chuàng)建SqlSessionFactory工廠 SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); //3.使用工廠生產(chǎn)SqlSession對(duì)象 SqlSession session = factory.openSession(); //4.使用SqlSession創(chuàng)建Dao接口的代理對(duì)象 IUserDao userDao = session.getMapper(IUserDao.class); //5.使用代理對(duì)象執(zhí)行方法 List<User> users = userDao.findAll(); for(User user : users){ System.out.println(user); } //6.釋放資源 session.close(); in.close(); }