private boolean applyAutomaticMappings( ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, String columnPrefix) throws SQLException { final List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix); boolean foundValues = false; for (String columnName : unmappedColumnNames) { String propertyName = columnName; if (columnPrefix != null && columnPrefix.length() > 0) { // When columnPrefix is specified, // ignore columns without the prefix. if (columnName.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) { propertyName = columnName.substring(columnPrefix.length()); } else { continue; } } final String property = metaObject.findProperty(propertyName, configuration.isMapUnderscoreToCamelCase()); if (property != null && metaObject.hasSetter(property)) { final Class<?> propertyType = metaObject.getSetterType(property); if (typeHandlerRegistry.hasTypeHandler(propertyType)) { final TypeHandler<?> typeHandler = rsw.getTypeHandler(propertyType, columnName); final Object value = typeHandler.getResult(rsw.getResultSet(), columnName); if (value != null || configuration.isCallSettersOnNulls()) { // issue #377, call setter on nulls if (value != null || !propertyType.isPrimitive()) { metaObject.setValue(property, value); } foundValues = true; } } } } return foundValues; }
public SqlCommand(Configuration configuration, Class<?> mapperInterface, Method method) { String statementName = mapperInterface.getName() + "." + method.getName(); MappedStatement ms = null; if (configuration.hasStatement(statementName)) { ms = configuration.getMappedStatement(statementName); } else if (!mapperInterface.equals(method.getDeclaringClass())) { // issue #35 String parentStatementName = method.getDeclaringClass().getName() + "." + method.getName(); if (configuration.hasStatement(parentStatementName)) { ms = configuration.getMappedStatement(parentStatementName); } } if (ms == null) { if (method.getAnnotation(Flush.class) != null) { name = null; type = SqlCommandType.FLUSH; } else { throw new BindingException("Invalid bound statement (not found): " + statementName); } } else { name = ms.getId(); type = ms.getSqlCommandType(); if (type == SqlCommandType.UNKNOWN) { throw new BindingException("Unknown execution method for: " + name); } } }
private void processGeneratedKeys(Executor executor, MappedStatement ms, Object parameter) { try { if (parameter != null && keyStatement != null && keyStatement.getKeyProperties() != null) { String keyProperty = keyStatement.getKeyProperties()[0]; // just one key property is supported final Configuration configuration = ms.getConfiguration(); final MetaObject metaParam = configuration.newMetaObject(parameter); if (keyProperty != null && metaParam.hasSetter(keyProperty)) { // Do not close keyExecutor. // The transaction will be closed by parent executor. Executor keyExecutor = configuration.newExecutor(executor.getTransaction(), ExecutorType.SIMPLE); List<Object> values = keyExecutor.query( keyStatement, parameter, RowBounds.DEFAULT, Executor.NO_RESULT_HANDLER); if (values.size() == 0) { throw new ExecutorException("SelectKey returned no data."); } else if (values.size() > 1) { throw new ExecutorException("SelectKey returned more than one value."); } else { metaParam.setValue(keyProperty, values.get(0)); } } } } catch (ExecutorException e) { throw e; } catch (Exception e) { throw new ExecutorException( "Error selecting key or setting result to parameter object. Cause: " + e, e); } }
/** * 构建ResultMap对象 * * @param id * @param clazz * @param configuration * @return */ private ResultMap buildResultMap(String id, Class<?> clazz, Configuration configuration) { // 判断是否已经存在缓存里 if (configuration.hasResultMap(id)) { return configuration.getResultMap(id); } List<ResultMapping> resultMappings = Lists.newArrayList(); Map<String, Field> columns = EntityUtil.getFields(clazz); for (Map.Entry<String, Field> column : columns.entrySet()) { Field field = column.getValue(); String fieldName = field.getName(); Class<?> columnTypeClass = resolveResultJavaType(clazz, fieldName, null); List<ResultFlag> flags = Lists.newArrayList(); if (field.isAnnotationPresent(Id.class)) { flags.add(ResultFlag.ID); } String columnName = column.getKey(); resultMappings.add( buildResultMapping(configuration, fieldName, columnName, columnTypeClass, flags)); } // 构建ResultMap ResultMap.Builder resultMapBuilder = new ResultMap.Builder(configuration, id, clazz, resultMappings); ResultMap rm = resultMapBuilder.build(); // 放到缓存中 configuration.addResultMap(rm); return rm; }
public Builder( Configuration configuration, String id, SqlSource sqlSource, SqlCommandType sqlCommandType) { mappedStatement.configuration = configuration; mappedStatement.id = id; mappedStatement.sqlSource = sqlSource; mappedStatement.statementType = StatementType.PREPARED; mappedStatement.parameterMap = new ParameterMap.Builder( configuration, "defaultParameterMap", null, new ArrayList<ParameterMapping>()) .build(); mappedStatement.resultMaps = new ArrayList<ResultMap>(); mappedStatement.timeout = configuration.getDefaultStatementTimeout(); mappedStatement.sqlCommandType = sqlCommandType; mappedStatement.keyGenerator = configuration.isUseGeneratedKeys() && SqlCommandType.INSERT.equals(sqlCommandType) ? new Jdbc3KeyGenerator() : new NoKeyGenerator(); String logId = id; if (configuration.getLogPrefix() != null) logId = configuration.getLogPrefix() + id; mappedStatement.statementLog = LogFactory.getLog(logId); mappedStatement.lang = configuration.getDefaultScriptingLanuageInstance(); }
/** * 使用DataSource初始化SqlSessionFactory * * @param ds */ public static void initialize(DataSource ds) { TransactionFactory transactionFactory = new MybatisTransactionFactory(); Environment environment = new Environment("snaker", transactionFactory, ds); Configuration configuration = new Configuration(environment); configuration.getTypeAliasRegistry().registerAliases(SCAN_PACKAGE, Object.class); if (log.isInfoEnabled()) { Map<String, Class<?>> typeAliases = configuration.getTypeAliasRegistry().getTypeAliases(); for (Entry<String, Class<?>> entry : typeAliases.entrySet()) { log.info( "Scanned class:[name=" + entry.getKey() + ",class=" + entry.getValue().getName() + "]"); } } try { for (String resource : resources) { InputStream in = Resources.getResourceAsStream(resource); XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, resource, configuration.getSqlFragments()); xmlMapperBuilder.parse(); } } catch (Exception e) { e.printStackTrace(); } finally { ErrorContext.instance().reset(); } sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); }
private void resolveTypeHandler() { if (resultMapping.typeHandler == null && resultMapping.javaType != null) { Configuration configuration = resultMapping.configuration; TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); resultMapping.typeHandler = typeHandlerRegistry.getTypeHandler(resultMapping.javaType, resultMapping.jdbcType); } }
/** 验证Statement */ private void validateStatement() { if (!config.hasStatement(commandName)) { throw new BindingException("Invalid bound statement (not found): " + commandName); } if (!config.hasStatement(commandCountName)) { throw new BindingException("Invalid bound statement (not found): " + commandCountName); } }
@Test(groups = {"tidb"}) public void shouldSuccessfullyLoadXMLMapperFile() throws Exception { Configuration configuration = new Configuration(); String resource = "org/apache/ibatis/builder/AuthorMapper.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments()); builder.parse(); }
private SessionFactory() { DataSource dataSource = SessionManager.getInstance().getDataSource(); TransactionFactory transactionFactory = new JdbcTransactionFactory(); Environment environment = new Environment("development", transactionFactory, dataSource); Configuration configuration = new Configuration(environment); configuration.addMapper(TableMapper.class); sqlMapper = new SqlSessionFactoryBuilder().build(configuration); }
public DynamicContext(Configuration configuration, Object parameterObject) { if (parameterObject != null && !(parameterObject instanceof Map)) { MetaObject metaObject = configuration.newMetaObject(parameterObject); bindings = new ContextMap(metaObject); } else { bindings = new ContextMap(null); } bindings.put(PARAMETER_OBJECT_KEY, parameterObject); bindings.put(DATABASE_ID_KEY, configuration.getDatabaseId()); }
/** * 对SQL参数(?)设值, 参考org.apache.ibatis.executor.parameter.DefaultParameterHandler。 * * @param ps 表示预编译的 SQL 语句的对象。 * @param mappedStatement MappedStatement * @param boundSql SQL * @param parameterObject 参数对象 * @throws java.sql.SQLException 数据库异常 */ @SuppressWarnings("unchecked") public static void setParameters( PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException { ErrorContext.instance() .activity("setting parameters") .object(mappedStatement.getParameterMap().getId()); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings != null) { Configuration configuration = mappedStatement.getConfiguration(); TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry(); MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject); for (int i = 0; i < parameterMappings.size(); i++) { ParameterMapping parameterMapping = parameterMappings.get(i); if (parameterMapping.getMode() != ParameterMode.OUT) { Object value; String propertyName = parameterMapping.getProperty(); PropertyTokenizer prop = new PropertyTokenizer(propertyName); if (parameterObject == null) { value = null; } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { value = parameterObject; } else if (boundSql.hasAdditionalParameter(propertyName)) { value = boundSql.getAdditionalParameter(propertyName); } else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX) && boundSql.hasAdditionalParameter(prop.getName())) { value = boundSql.getAdditionalParameter(prop.getName()); if (value != null) { value = configuration .newMetaObject(value) .getValue(propertyName.substring(prop.getName().length())); } } else { value = metaObject == null ? null : metaObject.getValue(propertyName); } @SuppressWarnings("rawtypes") TypeHandler typeHandler = parameterMapping.getTypeHandler(); if (typeHandler == null) { throw new ExecutorException( "There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId()); } typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType()); } } } }
private void makeSureGeneratedKeysAreNotUsedInBatchInserts(String statement) { Configuration configuration = session.getConfiguration(); if (null != configuration) { MappedStatement mappedStatement = configuration.getMappedStatement(statement); if (null != mappedStatement) { KeyGenerator keyGenerator = mappedStatement.getKeyGenerator(); if (keyGenerator instanceof Jdbc3KeyGenerator) { throw new IllegalStateException("Batch inserts cannot use generated keys"); } } } }
private Executor newExecutor() throws SQLException { final Environment environment = configuration.getEnvironment(); if (environment == null) throw new ExecutorException( "ResultLoader could not load lazily. Environment was not configured."); final DataSource ds = environment.getDataSource(); if (ds == null) throw new ExecutorException( "ResultLoader could not load lazily. DataSource was not configured."); final TransactionFactory transactionFactory = environment.getTransactionFactory(); final Transaction tx = transactionFactory.newTransaction(ds, null, false); return configuration.newExecutor(tx, ExecutorType.SIMPLE); }
private void loadMapper(Configuration configuration, String mapperName) { InputStream input = null; try { input = getClass().getResourceAsStream("/" + mapperName.replace('.', '/') + ".xml"); new XMLMapperBuilder(input, configuration, mapperName, configuration.getSqlFragments()) .parse(); configuration.addLoadedResource(mapperName); logback.setLoggerLevel(mapperName, Level.INFO); } catch (Exception e) { throw new IllegalArgumentException("Unable to load mapper " + mapperName, e); } finally { Closeables.closeQuietly(input); } }
private EnhancedResultObjectProxyImpl( Class<?> type, ResultLoaderMap lazyLoader, Configuration configuration, ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) { this.type = type; this.lazyLoader = lazyLoader; this.aggressive = configuration.isAggressiveLazyLoading(); this.lazyLoadTriggerMethods = configuration.getLazyLoadTriggerMethods(); this.objectFactory = objectFactory; this.constructorArgTypes = constructorArgTypes; this.constructorArgs = constructorArgs; }
// TODO: Not supported. @Test( groups = {"tidb-todo"}, enabled = false) public void shouldNotLoadTheSameNamespaceFromTwoResourcesWithDifferentNames() throws Exception { Configuration configuration = new Configuration(); String resource = "org/apache/ibatis/builder/AuthorMapper.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, "name1", configuration.getSqlFragments()); builder.parse(); InputStream inputStream2 = Resources.getResourceAsStream(resource); XMLMapperBuilder builder2 = new XMLMapperBuilder(inputStream2, configuration, "name2", configuration.getSqlFragments()); builder2.parse(); }
private boolean applyPropertyMappings( ResultSetWrapper rsw, ResultMap resultMap, MetaObject metaObject, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException { final List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix); boolean foundValues = false; final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings(); for (ResultMapping propertyMapping : propertyMappings) { final String column = prependPrefix(propertyMapping.getColumn(), columnPrefix); if (propertyMapping.isCompositeResult() || (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) || propertyMapping.getResultSet() != null) { Object value = getPropertyMappingValue( rsw.getResultSet(), metaObject, propertyMapping, lazyLoader, columnPrefix); final String property = propertyMapping.getProperty(); // issue #541 make property optional if (value != NO_VALUE && property != null && (value != null || configuration.isCallSettersOnNulls())) { // issue #377, call setter on nulls if (value != null || !metaObject.getSetterType(property).isPrimitive()) { metaObject.setValue(property, value); } foundValues = true; } } } return foundValues; }
/** 设置当前的参数的类型信息 */ private void setupCommandType() { MappedStatement ms = config.getMappedStatement(commandName); type = ms.getSqlCommandType(); if (type != SqlCommandType.SELECT) { throw new BindingException("Unsupport execution method for: " + commandName); } }
public BoundSql getBoundSql(Object parameterObject) { BoundSql boundSql = sqlSource.getBoundSql(parameterObject); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings == null || parameterMappings.size() <= 0) { boundSql = new BoundSql( configuration, boundSql.getSql(), parameterMap.getParameterMappings(), parameterObject); } // check for nested result maps in parameter mappings (issue #30) for (ParameterMapping pm : boundSql.getParameterMappings()) { String rmId = pm.getResultMapId(); if (rmId != null) { ResultMap rm = configuration.getResultMap(rmId); if (rm != null) { hasNestedResultMaps |= rm.hasNestedResultMaps(); } } } return boundSql; }
public CacheKey createCacheKey( MappedStatement ms, Object parameterObject, RowBounds rowBounds, BoundSql boundSql) { if (closed) throw new ExecutorException("Executor was closed."); CacheKey cacheKey = new CacheKey(); cacheKey.update(ms.getId()); cacheKey.update(rowBounds.getOffset()); cacheKey.update(rowBounds.getLimit()); cacheKey.update(boundSql.getSql()); List<ParameterMapping> parameterMappings = boundSql.getParameterMappings(); if (parameterMappings.size() > 0 && parameterObject != null) { TypeHandlerRegistry typeHandlerRegistry = ms.getConfiguration().getTypeHandlerRegistry(); if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) { cacheKey.update(parameterObject); } else { MetaObject metaObject = configuration.newMetaObject(parameterObject); for (ParameterMapping parameterMapping : parameterMappings) { String propertyName = parameterMapping.getProperty(); if (metaObject.hasGetter(propertyName)) { cacheKey.update(metaObject.getValue(propertyName)); } else if (boundSql.hasAdditionalParameter(propertyName)) { cacheKey.update(boundSql.getAdditionalParameter(propertyName)); } } } } return cacheKey; }
private Object getNestedQueryConstructorValue( ResultSet rs, ResultMapping constructorMapping, String columnPrefix) throws SQLException { final String nestedQueryId = constructorMapping.getNestedQueryId(); final MappedStatement nestedQuery = configuration.getMappedStatement(nestedQueryId); final Class<?> nestedQueryParameterType = nestedQuery.getParameterMap().getType(); final Object nestedQueryParameterObject = prepareParameterForNestedQuery( rs, constructorMapping, nestedQueryParameterType, columnPrefix); Object value = null; if (nestedQueryParameterObject != null) { final BoundSql nestedBoundSql = nestedQuery.getBoundSql(nestedQueryParameterObject); final CacheKey key = executor.createCacheKey( nestedQuery, nestedQueryParameterObject, RowBounds.DEFAULT, nestedBoundSql); final Class<?> targetType = constructorMapping.getJavaType(); final ResultLoader resultLoader = new ResultLoader( configuration, executor, nestedQuery, nestedQueryParameterObject, targetType, key, nestedBoundSql); value = resultLoader.loadResult(); } return value; }
private Object createParameterizedResultObject( ResultSetWrapper rsw, Class<?> resultType, List<ResultMapping> constructorMappings, List<Class<?>> constructorArgTypes, List<Object> constructorArgs, String columnPrefix) throws SQLException { boolean foundValues = false; for (ResultMapping constructorMapping : constructorMappings) { final Class<?> parameterType = constructorMapping.getJavaType(); final String column = constructorMapping.getColumn(); final Object value; if (constructorMapping.getNestedQueryId() != null) { value = getNestedQueryConstructorValue(rsw.getResultSet(), constructorMapping, columnPrefix); } else if (constructorMapping.getNestedResultMapId() != null) { final ResultMap resultMap = configuration.getResultMap(constructorMapping.getNestedResultMapId()); value = getRowValue(rsw, resultMap); } else { final TypeHandler<?> typeHandler = constructorMapping.getTypeHandler(); value = typeHandler.getResult(rsw.getResultSet(), prependPrefix(column, columnPrefix)); } constructorArgTypes.add(parameterType); constructorArgs.add(value); foundValues = value != null || foundValues; } return foundValues ? objectFactory.create(resultType, constructorArgTypes, constructorArgs) : null; }
private void createRowKeyForMappedProperties( ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey, List<ResultMapping> resultMappings, String columnPrefix) throws SQLException { for (ResultMapping resultMapping : resultMappings) { if (resultMapping.getNestedResultMapId() != null && resultMapping.getResultSet() == null) { // Issue #392 final ResultMap nestedResultMap = configuration.getResultMap(resultMapping.getNestedResultMapId()); createRowKeyForMappedProperties( nestedResultMap, rsw, cacheKey, nestedResultMap.getConstructorResultMappings(), prependPrefix(resultMapping.getColumnPrefix(), columnPrefix)); } else if (resultMapping.getNestedQueryId() == null) { final String column = prependPrefix(resultMapping.getColumn(), columnPrefix); final TypeHandler<?> th = resultMapping.getTypeHandler(); List<String> mappedColumnNames = rsw.getMappedColumnNames(resultMap, columnPrefix); if (column != null && mappedColumnNames.contains(column.toUpperCase(Locale.ENGLISH))) { // Issue #114 final Object value = th.getResult(rsw.getResultSet(), column); if (value != null) { cacheKey.update(column); cacheKey.update(value); } } } } }
private void createRowKeyForUnmappedProperties( ResultMap resultMap, ResultSetWrapper rsw, CacheKey cacheKey, String columnPrefix) throws SQLException { final MetaClass metaType = MetaClass.forClass(resultMap.getType()); List<String> unmappedColumnNames = rsw.getUnmappedColumnNames(resultMap, columnPrefix); for (String column : unmappedColumnNames) { String property = column; if (columnPrefix != null && columnPrefix.length() > 0) { // When columnPrefix is specified, // ignore columns without the prefix. if (column.toUpperCase(Locale.ENGLISH).startsWith(columnPrefix)) { property = column.substring(columnPrefix.length()); } else { continue; } } if (metaType.findProperty(property, configuration.isMapUnderscoreToCamelCase()) != null) { String value = rsw.getResultSet().getString(column); if (value != null) { cacheKey.update(column); cacheKey.update(value); } } } }
public List<Object> handleResultSets(Statement stmt) throws SQLException { final List<Object> multipleResults = new ArrayList<Object>(); int resultSetCount = 0; ResultSetWrapper rsw = getFirstResultSet(stmt); List<ResultMap> resultMaps = mappedStatement.getResultMaps(); int resultMapCount = resultMaps.size(); validateResultMapsCount(rsw, resultMapCount); while (rsw != null && resultMapCount > resultSetCount) { ResultMap resultMap = resultMaps.get(resultSetCount); handleResultSet(rsw, resultMap, multipleResults, null); rsw = getNextResultSet(stmt); cleanUpAfterHandlingResultSet(); resultSetCount++; } String[] resultSets = mappedStatement.getResulSets(); if (resultSets != null) { while (rsw != null && resultSetCount < resultSets.length) { ResultMapping parentMapping = nextResultMaps.get(resultSets[resultSetCount]); if (parentMapping != null) { String nestedResultMapId = parentMapping.getNestedResultMapId(); ResultMap resultMap = configuration.getResultMap(nestedResultMapId); handleResultSet(rsw, resultMap, null, parentMapping); } rsw = getNextResultSet(stmt); cleanUpAfterHandlingResultSet(); resultSetCount++; } } return collapseSingleResultList(multipleResults); }
private Object createResultObject( ResultSetWrapper rsw, ResultMap resultMap, ResultLoaderMap lazyLoader, String columnPrefix) throws SQLException { final List<Class<?>> constructorArgTypes = new ArrayList<Class<?>>(); final List<Object> constructorArgs = new ArrayList<Object>(); final Object resultObject = createResultObject(rsw, resultMap, constructorArgTypes, constructorArgs, columnPrefix); if (resultObject != null && !typeHandlerRegistry.hasTypeHandler(resultMap.getType())) { final List<ResultMapping> propertyMappings = resultMap.getPropertyResultMappings(); for (ResultMapping propertyMapping : propertyMappings) { if (propertyMapping.getNestedQueryId() != null && propertyMapping.isLazy()) { // issue gcode #109 && issue #149 return configuration .getProxyFactory() .createProxy( resultObject, lazyLoader, configuration, objectFactory, constructorArgTypes, constructorArgs); } } } return resultObject; }
public Builder(Configuration configuration, String property) { resultMapping.configuration = configuration; resultMapping.property = property; resultMapping.flags = new ArrayList<org.apache.ibatis.mapping.ResultFlag>(); resultMapping.composites = new ArrayList<org.apache.ibatis.mapping.ResultMapping>(); resultMapping.lazy = configuration.isLazyLoadingEnabled(); }
/** * 获取数据库类型 * * @param metaObject * @return 返回数据库类型的枚举对象 */ private Dialect.Type searchDbTypeByConfig(Configuration configuration) { String dialectConfig = configuration.getVariables().getProperty("dialect"); if (dialectConfig != null && !"".equals(dialectConfig)) { return Dialect.Type.valueOf(dialectConfig.toUpperCase()); } else { throw new RuntimeException("databaseType is null , please check your mybatis configuration!"); } }
public DefaultResultSetHandler( Executor executor, MappedStatement mappedStatement, ParameterHandler parameterHandler, ResultHandler resultHandler, BoundSql boundSql, RowBounds rowBounds) { this.executor = executor; this.configuration = mappedStatement.getConfiguration(); this.mappedStatement = mappedStatement; this.rowBounds = rowBounds; this.parameterHandler = parameterHandler; this.boundSql = boundSql; this.typeHandlerRegistry = configuration.getTypeHandlerRegistry(); this.objectFactory = configuration.getObjectFactory(); this.resultHandler = resultHandler; }