您好,登錄后才能下訂單哦!
MyBatis中binding 模塊的作用是什么,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來(lái)學(xué)習(xí)下,希望你能有所收獲。
org.apache.ibatis.binding
封裝ibatis編程模型 ibatis編程模型中,SqlSession作為sql執(zhí)行的入口,實(shí)用方法為sqlSession.selectOne(namespace+id, 參數(shù)列表)的形式(例:sqlSession.selectOne("com.enjoylearning.mybatis.mapper.TUserMapper.selectByPrimaryKey", 2)),不易于維護(hù)和閱讀
找到SqlSession中對(duì)應(yīng)的方法(insert|update|select)
找到命名空間和方法名(兩維坐標(biāo))
傳遞參數(shù)
MapperRegistry:mapper接口和對(duì)應(yīng)的代理工廠的注冊(cè)中心;是Configuration的成員變量
MapperProxyFactory:用于生成mapper接口動(dòng)態(tài)代理的實(shí)例對(duì)象;保證mapper實(shí)例對(duì)象是局部變量(為什么不緩存?見(jiàn)文章最后)
MapperMethod:封裝了Mapper接口中對(duì)應(yīng)的方法信息,以繼對(duì)應(yīng)sql語(yǔ)句的信息.MapperMethod對(duì)象不記錄任何狀態(tài),所以它可以再多個(gè)代理對(duì)象之間共享;sqlCommand:封裝sql語(yǔ)句;MtehodSignature:封裝mapper接口的入?yún)⒑头祷仡?lèi)型
個(gè)人理解
MapperRegistry的Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>(); key:mapper的Class對(duì)象 value:生產(chǎn)這個(gè)mapper的動(dòng)態(tài)代理示例的工廠
MapperProxyFactory:Map<Method, MapperMethod> methodCache key:方法的反射類(lèi) value 方法的信息(sql語(yǔ)句,入?yún)?返回值)
public class MapperRegistry { private final Configuration config;//config對(duì)象,mybatis全局唯一的 //記錄了mapper接口與對(duì)應(yīng)MapperProxyFactory之間的關(guān)系 private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>(); public MapperRegistry(Configuration config) { this.config = config; } @SuppressWarnings("unchecked") public <T> T getMapper(Class<T> type, SqlSession sqlSession) { final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type); if (mapperProxyFactory == null) { throw new BindingException("Type " + type + " is not known to the MapperRegistry."); } try { return mapperProxyFactory.newInstance(sqlSession); } catch (Exception e) { throw new BindingException("Error getting mapper instance. Cause: " + e, e); }
/** * * 用于生成mapper接口動(dòng)態(tài)代理的實(shí)例對(duì)象; * @author Lasse Voss */ public class MapperProxyFactory<T> { //mapper接口的class對(duì)象 private final Class<T> mapperInterface; //key是mapper接口中的某個(gè)方法的method對(duì)象,value是對(duì)應(yīng)的MapperMethod,MapperMethod對(duì)象不記錄任何狀態(tài)信息,所以它可以在多個(gè)代理對(duì)象之間共享 private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<>();
public class MapperMethod { //從configuration中獲取方法的命名空間.方法名以及SQL語(yǔ)句的類(lèi)型 private final SqlCommand command; //封裝mapper接口方法的相關(guān)信息(入?yún)?,返回?lèi)型); private final MethodSignature method;
public class MapperProxyFactory<T> { //mapper接口的class對(duì)象 private final Class<T> mapperInterface; //key是mapper接口中的某個(gè)方法的method對(duì)象,value是對(duì)應(yīng)的MapperMethod,MapperMethod對(duì)象不記錄任何狀態(tài)信息,所以它可以在多個(gè)代理對(duì)象之間共享 private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<>(); public MapperProxyFactory(Class<T> mapperInterface) { this.mapperInterface = mapperInterface; } public Class<T> getMapperInterface() { return mapperInterface; } public Map<Method, MapperMethod> getMethodCache() { return methodCache; } @SuppressWarnings("unchecked") protected T newInstance(MapperProxy<T> mapperProxy) { //創(chuàng)建實(shí)現(xiàn)了mapper接口的動(dòng)態(tài)代理對(duì)象 return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy); } public T newInstance(SqlSession sqlSession) { //每次調(diào)用都會(huì)創(chuàng)建新的MapperProxy對(duì)象 final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache); return newInstance(mapperProxy); } }
兩個(gè)newInstance方法生成mapper的動(dòng)態(tài)代理對(duì)象MapperProxy
public class MapperProxy<T> implements InvocationHandler, Serializable { ....... @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { try { if (Object.class.equals(method.getDeclaringClass())) {//如果是Object本身的方法不增強(qiáng) return method.invoke(this, args); } else if (isDefaultMethod(method)) { return invokeDefaultMethod(proxy, method, args); } } catch (Throwable t) { throw ExceptionUtil.unwrapThrowable(t); } //從緩存中獲取mapperMethod對(duì)象,如果緩存中沒(méi)有,則創(chuàng)建一個(gè),并添加到緩存中 final MapperMethod mapperMethod = cachedMapperMethod(method); //調(diào)用execute方法執(zhí)行sql return mapperMethod.execute(sqlSession, args); } private MapperMethod cachedMapperMethod(Method method) { return methodCache.computeIfAbsent(method, k -> new MapperMethod(mapperInterface, method, sqlSession.getConfiguration())); }
從invoke方法可以看出 是mapperMethod調(diào)用了execute方法
public class MapperMethod { ...... public Object execute(SqlSession sqlSession, Object[] args) { Object result; //根據(jù)sql語(yǔ)句類(lèi)型以及接口返回的參數(shù)選擇調(diào)用不同的 switch (command.getType()) { case INSERT: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.insert(command.getName(), param)); break; } case UPDATE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.update(command.getName(), param)); break; } case DELETE: { Object param = method.convertArgsToSqlCommandParam(args); result = rowCountResult(sqlSession.delete(command.getName(), param)); break; } case SELECT: if (method.returnsVoid() && method.hasResultHandler()) {//返回值為void executeWithResultHandler(sqlSession, args); result = null; } else if (method.returnsMany()) {//返回值為集合或者數(shù)組 result = executeForMany(sqlSession, args); } else if (method.returnsMap()) {//返回值為map result = executeForMap(sqlSession, args); } else if (method.returnsCursor()) {//返回值為游標(biāo) result = executeForCursor(sqlSession, args); } else {//處理返回為單一對(duì)象的情況 //通過(guò)參數(shù)解析器解析解析參數(shù) Object param = method.convertArgsToSqlCommandParam(args); result = sqlSession.selectOne(command.getName(), param); if (method.returnsOptional() && (result == null || !method.getReturnType().equals(result.getClass()))) { result = OptionalUtil.ofNullable(result); } } break; case FLUSH: result = sqlSession.flushStatements(); break; default: throw new BindingException("Unknown execution method for: " + command.getName()); } if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) { throw new BindingException("Mapper method '" + command.getName() + " attempted to return null from a method with a primitive return type (" + method.getReturnType() + ")."); } return result; }
重點(diǎn)看 result = sqlSession.selectOne(command.getName(), param); 這里使用了ibatis的用法
mapperProxy做查詢(xún)依賴(lài)的還是sqlSession.按照現(xiàn)在的代碼結(jié)構(gòu)來(lái)說(shuō),如果緩存了mapperProxy,當(dāng)sqlSession失效,mapperProxy也就失效了. 如果修改代結(jié)構(gòu),那么sqlSession就要作為查詢(xún)參數(shù)
// 原本 TUser user = mapper.selectByPrimaryKey(2); // 修改后的寫(xiě)法 TUser user = mapper.selectByPrimaryKey(sqslSession,2);
看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請(qǐng)關(guān)注億速云行業(yè)資訊頻道,感謝您對(duì)億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。