Java 类org.apache.ibatis.session.Configuration 实例源码

项目:mybatis-plus-mini    文件:SqlExplainInterceptor.java   
public Object intercept(Invocation invocation) throws Throwable {
    /**
     * 处理 DELETE UPDATE 语句
     */
    MappedStatement ms = (MappedStatement) invocation.getArgs()[0];
    if (ms.getSqlCommandType() == SqlCommandType.DELETE || ms.getSqlCommandType() == SqlCommandType.UPDATE) {
        Executor executor = (Executor) invocation.getTarget();
        Configuration configuration = ms.getConfiguration();
        Object parameter = invocation.getArgs()[1];
        BoundSql boundSql = ms.getBoundSql(parameter);
        Connection connection = executor.getTransaction().getConnection();
        String databaseVersion = connection.getMetaData().getDatabaseProductVersion();
        if (GlobalConfigUtils.getDbType(configuration).equals(DBType.MYSQL)
                && VersionUtils.compare(minMySQLVersion, databaseVersion)) {
            logger.warn("Warn: Your mysql version needs to be greater than '5.6.3' to execute of Sql Explain!");
            return invocation.proceed();
        }
        /**
         * 执行 SQL 分析
         */
        sqlExplain(configuration, ms, boundSql, connection, parameter);
    }
    return invocation.proceed();
}
项目:nighthawk    文件:MybatisTracingInterceptor.java   
@Override
public Object intercept(Invocation invocation) throws Throwable {
    if (!statementTracer.isTraceEnabled()) {
        return invocation.proceed();
    }
    MetaObject metaObject = MetaObjectUtils.findTargetObject(invocation);
    BoundSql boundSql = MetaObjectUtils.getBoundSql(metaObject);
    Configuration configuration = MetaObjectUtils.getConfiguration(metaObject);
    Exception queryException = null;
    try {
        beginTrace(boundSql.getSql(), configuration.getEnvironment());
        return invocation.proceed();
    } catch (Exception ex) {
        queryException = ex;
        throw ex;
    } finally {
        statementTracer.endTrace(0, queryException);
    }
}
项目:OftenPorter    文件:MyBatisDaoGen.java   
void bindAlias(_MyBatis myBatis)
{
    SqlSessionFactory sqlSessionFactory = mybatisConfig.mSqlSessionFactoryBuilder.getFactory();
    Configuration configuration = sqlSessionFactory.getConfiguration();
    TypeAliasRegistry typeAliasRegistry = configuration.getTypeAliasRegistry();

    if (WPTool.notNullAndEmpty(myBatis.daoAlias))
    {
        typeAliasRegistry.registerAlias(myBatis.daoAlias, myBatis.daoClass);
    } else if (myBatis.isAutoAlias)
    {
        typeAliasRegistry.registerAlias(myBatis.daoClass);
    }

    if (!myBatis.entityClass.equals(MyBatis.class))
    {
        if (WPTool.notNullAndEmpty(myBatis.entityAlias))
        {
            typeAliasRegistry.registerAlias(myBatis.entityAlias, myBatis.entityClass);
        } else if (myBatis.isAutoAlias)
        {
            typeAliasRegistry.registerAlias(myBatis.entityClass);
        }
    }

}
项目:MybatisGeneatorUtil    文件:MapperTemplate.java   
@Deprecated
public IfSqlNode ExampleValidSqlNode(Configuration configuration) {
    List<SqlNode> whenSqlNodes = new ArrayList<SqlNode>();
    IfSqlNode noValueSqlNode = new IfSqlNode(new TextSqlNode(" and ${criterion.condition}"), "criterion.noValue");
    whenSqlNodes.add(noValueSqlNode);
    IfSqlNode singleValueSqlNode = new IfSqlNode(new TextSqlNode(" and ${criterion.condition} #{criterion.value}"), "criterion.singleValue");
    whenSqlNodes.add(singleValueSqlNode);
    IfSqlNode betweenValueSqlNode = new IfSqlNode(new TextSqlNode(" and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}"), "criterion.betweenValue");
    whenSqlNodes.add(betweenValueSqlNode);

    List<SqlNode> listValueContentSqlNodes = new ArrayList<SqlNode>();
    listValueContentSqlNodes.add(new TextSqlNode(" and ${criterion.condition}"));
    ForEachSqlNode listValueForEachSqlNode = new ForEachSqlNode(configuration, new StaticTextSqlNode("#{listItem}"), "criterion.value", null, "listItem", "(", ")", ",");
    listValueContentSqlNodes.add(listValueForEachSqlNode);
    IfSqlNode listValueSqlNode = new IfSqlNode(new MixedSqlNode(listValueContentSqlNodes), "criterion.listValue");
    whenSqlNodes.add(listValueSqlNode);

    ChooseSqlNode chooseSqlNode = new ChooseSqlNode(whenSqlNodes, null);

    ForEachSqlNode criteriaSqlNode = new ForEachSqlNode(configuration, chooseSqlNode, "criteria.criteria", null, "criterion", null, null, null);

    TrimSqlNode trimSqlNode = new TrimSqlNode(configuration, criteriaSqlNode, "(", "and", ")", null);
    IfSqlNode validSqlNode = new IfSqlNode(trimSqlNode, "criteria.valid");
    return validSqlNode;
}
项目:alfresco-core    文件:RollupResultHandler.java   
/**
 * @param keyProperties         the properties that make up the unique key
 * @param collectionProperty    the property mapped using a nested <b>ResultMap</b>
 * @param resultHandler         the result handler that will receive the rolled-up results
 * @param maxResults            the maximum number of results to retrieve (-1 for no limit).
 *                              Make sure that the query result limit is large enough to produce this
 *                              at least this number of results
 */
public RollupResultHandler(Configuration configuration, String[] keyProperties, String collectionProperty, ResultHandler resultHandler, int maxResults)
{
    if (keyProperties == null || keyProperties.length == 0)
    {
        throw new IllegalArgumentException("RollupRowHandler can only be used with at least one key property.");
    }
    if (collectionProperty == null)
    {
        throw new IllegalArgumentException("RollupRowHandler must have a collection property.");
    }
    this.configuration = configuration;
    this.keyProperties = keyProperties;
    this.collectionProperty = collectionProperty;
    this.resultHandler = resultHandler;
    this.maxResults = maxResults;
    this.rawResults = new ArrayList<Object>(100);
}
项目:alfresco-core    文件:RollupResultHandler.java   
@SuppressWarnings("unchecked")
private static Object coalesceResults(Configuration configuration, List<Object> valueObjects, String collectionProperty)
{
    // Take the first result as the base value
    Object resultObject = null;
    MetaObject probe = null;
    Collection<Object> collection = null;
    for (Object object : valueObjects)
    {
        if (collection == null)
        {
            resultObject = object;
            probe = configuration.newMetaObject(resultObject);
            collection = (Collection<Object>) probe.getValue(collectionProperty);
        }
        else
        {
            Collection<?> addedValues = (Collection<Object>) probe.getValue(collectionProperty);
            collection.addAll(addedValues);
        }
    }
    // Done
    return resultObject;
}
项目:dropwizard-mybatis    文件:MyBatisFactory.java   
/**
 * Create an instance of MyBatis.
 *
 * @param environment The dropwizard environment
 * @param configuration The data source factory/configuration
 * @param dataSource The datasource you want to use.
 * @param name The name of this mybatis factory used for metrics
 * @return An instance of MyBatis.
 */
public final SqlSessionFactory build(Environment environment,
        DataSourceFactory configuration,
        ManagedDataSource dataSource,
        String name) {
    // Initialize validation query
    final String validationQuery = configuration.getValidationQuery();

    // Build mybatis session factory
    TransactionFactory transactionFactory = new JdbcTransactionFactory();
    org.apache.ibatis.mapping.Environment myBatisEnvironment =
            new org.apache.ibatis.mapping.Environment(ENV_NAME, transactionFactory, dataSource);
    Configuration mybatisConfiguration = new Configuration(myBatisEnvironment);
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(mybatisConfiguration);

    // Setup managed data source and health checks
    environment.lifecycle().manage(dataSource);
    environment.healthChecks().register(name, new MyBatisHealthCheck(sessionFactory, validationQuery));

    return sessionFactory;
}
项目:tk-mybatis    文件:MapperHelper.java   
/**
 * 配置指定的接口
 *
 * @param configuration
 * @param mapperInterface
 */
public void processConfiguration(Configuration configuration, Class<?> mapperInterface) {
    String prefix;
    if (mapperInterface != null) {
        prefix = mapperInterface.getCanonicalName();
    } else {
        prefix = "";
    }
    for (Object object : new ArrayList<Object>(configuration.getMappedStatements())) {
        if (object instanceof MappedStatement) {
            MappedStatement ms = (MappedStatement) object;
            if (ms.getId().startsWith(prefix) && isMapperMethod(ms.getId())) {
                if (ms.getSqlSource() instanceof ProviderSqlSource) {
                    setSqlSource(ms);
                }
            }
        }
    }
}
项目:tk-mybatis    文件:MapperTemplate.java   
@Deprecated
public IfSqlNode ExampleValidSqlNode(Configuration configuration) {
    List<SqlNode> whenSqlNodes = new ArrayList<SqlNode>();
    IfSqlNode noValueSqlNode = new IfSqlNode(new TextSqlNode(" and ${criterion.condition}"), "criterion.noValue");
    whenSqlNodes.add(noValueSqlNode);
    IfSqlNode singleValueSqlNode = new IfSqlNode(new TextSqlNode(" and ${criterion.condition} #{criterion.value}"), "criterion.singleValue");
    whenSqlNodes.add(singleValueSqlNode);
    IfSqlNode betweenValueSqlNode = new IfSqlNode(new TextSqlNode(" and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}"), "criterion.betweenValue");
    whenSqlNodes.add(betweenValueSqlNode);

    List<SqlNode> listValueContentSqlNodes = new ArrayList<SqlNode>();
    listValueContentSqlNodes.add(new TextSqlNode(" and ${criterion.condition}"));
    ForEachSqlNode listValueForEachSqlNode = new ForEachSqlNode(configuration, new StaticTextSqlNode("#{listItem}"), "criterion.value", null, "listItem", "(", ")", ",");
    listValueContentSqlNodes.add(listValueForEachSqlNode);
    IfSqlNode listValueSqlNode = new IfSqlNode(new MixedSqlNode(listValueContentSqlNodes), "criterion.listValue");
    whenSqlNodes.add(listValueSqlNode);

    ChooseSqlNode chooseSqlNode = new ChooseSqlNode(whenSqlNodes, null);

    ForEachSqlNode criteriaSqlNode = new ForEachSqlNode(configuration, chooseSqlNode, "criteria.criteria", null, "criterion", null, null, null);

    TrimSqlNode trimSqlNode = new TrimSqlNode(configuration, criteriaSqlNode, "(", "and", ")", null);
    IfSqlNode validSqlNode = new IfSqlNode(trimSqlNode, "criteria.valid");
    return validSqlNode;
}
项目:taskana    文件:TaskanaEngineImpl.java   
/**
 * This method creates the sqlSessionManager of myBatis. It integrates all the SQL mappers
 *
 * @return a {@link SqlSessionFactory}
 */
private SqlSessionManager createSqlSessionManager() {
    Environment environment = new Environment(DEFAULT, this.transactionFactory,
        taskanaEngineConfiguration.getDatasource());
    Configuration configuration = new Configuration(environment);
    // add mappers
    configuration.addMapper(TaskMapper.class);
    configuration.addMapper(TaskMonitorMapper.class);
    configuration.addMapper(WorkbasketMapper.class);
    configuration.addMapper(DistributionTargetMapper.class);
    configuration.addMapper(ClassificationMapper.class);
    configuration.addMapper(WorkbasketAccessMapper.class);
    configuration.addMapper(ObjectReferenceMapper.class);
    configuration.addMapper(QueryMapper.class);
    configuration.addMapper(AttachmentMapper.class);
    configuration.getTypeHandlerRegistry().register(MapTypeHandler.class);
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(configuration);
    SqlSessionManager sessionManager = SqlSessionManager.newInstance(sessionFactory);
    return sessionManager;
}
项目:mumu    文件:MapperScanApplication.java   
public void init() throws IOException, SAXException, ParserConfigurationException, ClassNotFoundException {
    log.info("parse " + configLocation);
    // 解析xml
    InputStream inputStream=MapperScanApplication.class.getClassLoader().getResourceAsStream(configLocation);

    Configuration configuration = sqlSessionFactory.getConfiguration();

    if(inputStream==null){
        return;
    }
    XPathParser xPathParser = new XPathParser(inputStream);
    XNode root = xPathParser.evalNode("/configuration");

    handleSetting(configuration, root);

    handleTypeAlias(configuration, root);

    handleMappers(configuration, root);
}
项目:hibatis    文件:SqlBuilder.java   
public SqlNode selectUnionAll(Configuration configuration, String conditions, String orderBy, LockMode lockMode) {
    String sql = select(conditions, orderBy).toString();
    StringBuffer sqlSb = new StringBuffer();
    Matcher matcher = ARGUMENT_REGEX.matcher(sql);
    while (matcher.find()) {
        String name = matcher.group(1);
        matcher.appendReplacement(sqlSb, "#{item." + name + "}");
    }
    matcher.appendTail(sqlSb);
    if (lockMode == LockMode.UPGRADE) {
        sqlSb.append(" FOR UPDATE");
    } else if (lockMode == LockMode.UPGRADE_NOWAIT) {
        sqlSb.append(" FOR UPDATE NOWAIT");
    }
    SqlNode contents = new TextSqlNode(sqlSb.toString());
    String collectionExpression = "list";
    String index = "index";
    String item = "item";
    String open = "";
    String close = "";
    String separator = " UNION ALL ";
    return new ForEachSqlNode(configuration, contents, collectionExpression, index, item, open, close, separator);
}
项目:spring-boot-starter-dao    文件:CustomPageInterceptor.java   
@Override
public Object intercept(Invocation invocation) throws Throwable {
    Object object=invocation.getArgs()[0];
    if(object instanceof MappedStatement){
        MappedStatement  statement=(MappedStatement) object;
        Configuration config = statement.getConfiguration();
        DataSource dataSource= config.getEnvironment().getDataSource();
        if(dataSource instanceof DynamicDataSource){
            DynamicDataSource dynamicDataSource=((DynamicDataSource)dataSource); 
            Dialect dialect= dynamicDataSource.getDialect();
            if(pageHelpers.containsKey(dialect)){
                log.debug("将使用{}的PageHelper....",dialect);
                return pageHelpers.get(dialect).intercept(invocation);
            }else{
                log.debug("将使用默认的PageHelper,dialect=({})的....",this.dialect);
            }
        }else{
            log.debug("将使用默认的PageHelper,dialect=({})的....",this.dialect);
        }
    }else{
        log.debug("将使用默认的PageHelper,dialect=({})的....",this.dialect);
    }
    return pageHelper.intercept(invocation);
}
项目:spring-boot-starter-dao    文件:AbstractDataBaseBean.java   
protected final AbstractBeanDefinition createSqlSessionFactoryBean(String dataSourceName, String mapperPackage,
        String typeAliasesPackage, Dialect dialect, Configuration configuration) {
    configuration.setDatabaseId(dataSourceName);
    BeanDefinitionBuilder bdb = BeanDefinitionBuilder.rootBeanDefinition(SqlSessionFactoryBean.class);
    bdb.addPropertyValue("configuration", configuration);
    bdb.addPropertyValue("failFast", true);
    bdb.addPropertyValue("typeAliases", this.saenTypeAliases(typeAliasesPackage));
    bdb.addPropertyReference("dataSource", dataSourceName);
    bdb.addPropertyValue("plugins", new Interceptor[] { new CustomPageInterceptor(dialect) });
    if (!StringUtils.isEmpty(mapperPackage)) {
        try {
            mapperPackage = new StandardEnvironment().resolveRequiredPlaceholders(mapperPackage);
            String mapperPackages = ClassUtils.convertClassNameToResourcePath(mapperPackage);
            String mapperPackagePath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + mapperPackages + "/*.xml";
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources(mapperPackagePath);
            bdb.addPropertyValue("mapperLocations", resources);
        } catch (Exception e) {
            log.error("初始化失败", e);
            throw new RuntimeException( String.format("SqlSessionFactory 初始化失败  mapperPackage=%s", mapperPackage + ""));
        }
    }
    return bdb.getBeanDefinition();
}
项目:azeroth    文件:UpdateBuilder.java   
/**
 * @param configuration
 * @param entity
 */
public static void build(Configuration configuration, LanguageDriver languageDriver,
                         EntityInfo entity) {
    String[] names = GeneralSqlGenerator.methodDefines.updateName().split(",");
    for (String name : names) {
        String msId = entity.getMapperClass().getName() + "." + name;

        EntityMapper entityMapper = EntityHelper.getEntityMapper(entity.getEntityClass());

        String sql = buildUpdateSql(entityMapper, name.endsWith("Selective"));

        SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql,
                entity.getEntityClass());

        MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration,
                msId, sqlSource, SqlCommandType.UPDATE);

        MappedStatement statement = statementBuilder.build();

        configuration.addMappedStatement(statement);
    }
}
项目:azeroth    文件:DeleteBuilder.java   
/**
 * @param configuration
 * @param entity
 */
public static void build(Configuration configuration, LanguageDriver languageDriver, EntityInfo entity) {
    String msId = entity.getMapperClass().getName() + "." + GeneralSqlGenerator.methodDefines.deleteName();

    // 从参数对象里提取注解信息
    EntityMapper entityMapper = EntityHelper.getEntityMapper(entity.getEntityClass());
    // 生成sql
    String sql = buildDeleteSql(entityMapper);

    SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, entity.getEntityClass());

    MappedStatement.Builder statementBuilder = new MappedStatement.Builder(configuration, msId, sqlSource, SqlCommandType.DELETE);

    MappedStatement statement = statementBuilder.build();
    configuration.addMappedStatement(statement);
}
项目:kettle_support_kettle8.0    文件:PaginationMapperProxy.java   
@Override
public Object invoke(Object proxy, Method method, Object[] args)
        throws Throwable {
    if (isObjectMethod(method)) {
        return null;
    }
    final Class<?> declaringInterface = findDeclaringInterface(proxy,
            method);
    if (Pagination.class.isAssignableFrom(method.getReturnType())) {
        // 分页处理
        return new PaginationMapperMethod(declaringInterface, method,
                sqlSession).execute(args);
    }
    // 原处理方式
    final MapperMethod mapperMethod = new MapperMethod(declaringInterface,
            method, (Configuration) sqlSession.getConfiguration());
    final Object result = mapperMethod.execute(sqlSession, args);
    if (result == null && method.getReturnType().isPrimitive()) {
        throw new BindingException(
                "Mapper method '"
                        + method.getName()
                        + "' ("
                        + method.getDeclaringClass()
                        + ") attempted to return null from a method with a primitive return type ("
                        + method.getReturnType() + ").");
    }
    return result;
}
项目:mybatis-plus-mini    文件:MybatisMapperRefresh.java   
/**
 * 刷新mapper
 *
 * @throws Exception
 */
@SuppressWarnings("rawtypes")
private void refresh(Resource resource) throws ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
    this.configuration = sqlSessionFactory.getConfiguration();
    boolean isSupper = configuration.getClass().getSuperclass() == Configuration.class;
    try {
        Field loadedResourcesField = isSupper ? configuration.getClass().getSuperclass().getDeclaredField("loadedResources")
                : configuration.getClass().getDeclaredField("loadedResources");
        loadedResourcesField.setAccessible(true);
        Set loadedResourcesSet = ((Set) loadedResourcesField.get(configuration));
        XPathParser xPathParser = new XPathParser(resource.getInputStream(), true, configuration.getVariables(),
                new XMLMapperEntityResolver());
        XNode context = xPathParser.evalNode("/mapper");
        String namespace = context.getStringAttribute("namespace");
        Field field = MapperRegistry.class.getDeclaredField("knownMappers");
        field.setAccessible(true);
        Map mapConfig = (Map) field.get(configuration.getMapperRegistry());
        mapConfig.remove(Resources.classForName(namespace));
        loadedResourcesSet.remove(resource.toString());
        configuration.getCacheNames().remove(namespace);
        cleanParameterMap(context.evalNodes("/mapper/parameterMap"), namespace);
        cleanResultMap(context.evalNodes("/mapper/resultMap"), namespace);
        cleanKeyGenerators(context.evalNodes("insert|update"), namespace);
        cleanSqlElement(context.evalNodes("/mapper/sql"), namespace);
        XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resource.getInputStream(),
                sqlSessionFactory.getConfiguration(), // 注入的sql先不进行处理了
                resource.toString(), sqlSessionFactory.getConfiguration().getSqlFragments());
        xmlMapperBuilder.parse();
        logger.debug("refresh: '" + resource + "', success!");
    } catch (IOException e) {
        logger.error("Refresh IOException :" + e.getMessage());
    } finally {
        ErrorContext.instance().reset();
    }
}
项目:otus_java_2017_04    文件:MainAnnotationsExample.java   
private SqlSessionFactory getSqlSessionFactory(DataSource dataSource) {
    TransactionFactory transactionFactory = new JdbcTransactionFactory();
    Environment environment = new Environment("development", transactionFactory, dataSource);
    Configuration configuration = new Configuration(environment);

    configuration.addMapper(UsersDAO.class);

    return new SqlSessionFactoryBuilder().build(configuration);
}
项目:mybatis-plus-mini    文件:MybatisXMLMapperBuilder.java   
private MybatisXMLMapperBuilder(XPathParser parser, Configuration configuration, String resource, Map<String, XNode> sqlFragments) {
    super(configuration);
    this.builderAssistant = new MapperBuilderAssistant(configuration, resource);
    this.parser = parser;
    this.sqlFragments = sqlFragments;
    this.resource = resource;
}
项目:mybatis-plus-mini    文件:MybatisMapperAnnotationBuilder.java   
public MybatisMapperAnnotationBuilder(Configuration configuration, Class<?> type) {
    // TODO 执行父类
    super(configuration, type);
    String resource = type.getName().replace('.', '/') + ".java (best guess)";
    this.assistant = new MapperBuilderAssistant(configuration, resource);
    this.configuration = configuration;
    this.type = type;
    sqlAnnotationTypes.add(Select.class);
    sqlAnnotationTypes.add(Insert.class);
    sqlAnnotationTypes.add(Update.class);
    sqlAnnotationTypes.add(Delete.class);
    sqlProviderAnnotationTypes.add(SelectProvider.class);
    sqlProviderAnnotationTypes.add(InsertProvider.class);
    sqlProviderAnnotationTypes.add(UpdateProvider.class);
    sqlProviderAnnotationTypes.add(DeleteProvider.class);
}
项目:mybatis-plus-mini    文件:TableInfoHelper.java   
/**
 * 初始化SqlSessionFactory (供Mybatis原生调用)
 *
 * @param sqlSessionFactory
 * @return
 */
public static void initSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
    Configuration configuration = sqlSessionFactory.getConfiguration();
    GlobalConfiguration globalConfig = GlobalConfigUtils.getGlobalConfig(configuration);
    // SqlRunner
    Column.FACTORY = sqlSessionFactory;
    if (globalConfig == null) {
        GlobalConfiguration defaultCache = GlobalConfigUtils.defaults();
        defaultCache.setSqlSessionFactory(sqlSessionFactory);
        GlobalConfigUtils.setGlobalConfig(configuration, defaultCache);
    } else {
        globalConfig.setSqlSessionFactory(sqlSessionFactory);
    }
}
项目:mybatis-plus-mini    文件:GlobalConfigUtils.java   
/**
 * 获取MybatisGlobalConfig (统一所有入口)
 *
 * @param configuration
 * @return
 */
public static GlobalConfiguration getGlobalConfig(Configuration configuration) {
    if (configuration == null) {
        throw new MybatisPlusException("Error: You need Initialize MybatisConfiguration !");
    }
    return getGlobalConfig(configuration.toString());
}
项目:mybatis-plus-mini    文件:GlobalConfigUtils.java   
public static ISqlInjector getSqlInjector(Configuration configuration) {
    // fix #140
    GlobalConfiguration globalConfiguration = getGlobalConfig(configuration);
    ISqlInjector sqlInjector = globalConfiguration.getSqlInjector();
    if (sqlInjector == null) {
        sqlInjector = new AutoSqlInjector();
        globalConfiguration.setSqlInjector(sqlInjector);
    }
    return sqlInjector;
}
项目:mybatis-typehandlers-postgis    文件:PointTypeHandlerTest.java   
@BeforeClass
public static void setUp() throws Exception{
    setupSqlSessionFactory("com/eyougo/mybatis/postgis/type/PointTypeHandlerTest.sql");
    Configuration configuration = sqlSessionFactory.getConfiguration();
    configuration.getTypeHandlerRegistry().register(PointTypeHandler.class);
    configuration.addMapper(PointMapper.class);
}
项目:mybatis-plus-mini    文件:SqlHelper.java   
/**
 * 获取sqlSessionå
 *
 * @param clazz
 * @return
 */
private static SqlSession getSqlSession(Class<?> clazz) {
    SqlSession session = null;
    try {
        SqlSessionFactory sqlSessionFactory = GlobalConfigUtils.currentSessionFactory(clazz);
        Configuration configuration = sqlSessionFactory.getConfiguration();
        session = GlobalConfigUtils.getGlobalConfig(configuration).getSqlSession();
    } catch (Exception e) {
        // ignored
    }
    return session;
}
项目:mybatis-plus-mini    文件:MybatisXMLConfigBuilder.java   
public Configuration parse() {
    if (parsed) {
        throw new BuilderException("Each XMLConfigBuilder can only be used once.");
    }
    parsed = true;
    parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
}
项目:mybatis-plus-mini    文件:MybatisXMLConfigBuilder.java   
private Properties settingsAsProperties(XNode context) {
    if (context == null) {
        return new Properties();
    }
    Properties props = context.getChildrenAsProperties();
    // Check that all settings are known to the configuration class
    MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
    for (Object key : props.keySet()) {
        if (!metaConfig.hasSetter(String.valueOf(key))) {
            throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
        }
    }
    return props;
}
项目:mybatis-plus-mini    文件:MySqlInjector.java   
@Override
public void inject(Configuration configuration, MapperBuilderAssistant builderAssistant, Class<?> mapperClass,
                   Class<?> modelClass, TableInfo table) {
    /* 添加一个自定义方法 */
    deleteAllUser(mapperClass, modelClass, table);
    // 测试 com.baomidou.mybatisplus.test.mysql.MetaObjectHandlerTest
    deleteLogicById(mapperClass, modelClass, table);
}
项目:xproject    文件:PaginationInterceptor.java   
public Object intercept(Invocation invocation) throws Throwable {
    StatementHandler statementHandler = (StatementHandler)invocation.getTarget();
    MetaObject metaStatementHandler = MetaObject.forObject(statementHandler, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(), new DefaultReflectorFactory());
    RowBounds rowBounds = (RowBounds)metaStatementHandler.getValue("delegate.rowBounds");
    if(rowBounds == null || rowBounds == RowBounds.DEFAULT){
        return invocation.proceed();
    }
    if(dialect == null){
        Configuration configuration = (Configuration) metaStatementHandler.getValue("delegate.configuration");
        Dialect.Type databaseType = null;
        String d = configuration.getVariables().getProperty("dialect");
        if(d == null || d.trim().equals("")){
            throw new IllegalStateException("No property named with 'dialect' defined in mybatis configuration xml file.");
        }
        try {
            databaseType = Dialect.Type.valueOf(d);
        } catch (Exception e) {
            throw new IllegalStateException(String.format("No such dialect enum defined in class %s.", Dialect.Type.class));
        }

        switch (databaseType) {
            case MYSQL: // MySQL分页
                dialect = new MySQLDialect();
                break;
            case ORACLE: // Oracle分页
                dialect = new OracleDialect();
                break;
        }
        if(dialect == null){
            throw new IllegalStateException(String.format("No %s dialect found!", databaseType));
        }
    }
    String originalSql = metaStatementHandler.getValue("delegate.boundSql.sql").toString();
    metaStatementHandler.setValue("delegate.boundSql.sql", dialect.getLimitSql(originalSql, rowBounds.getOffset(), rowBounds.getLimit()));
    metaStatementHandler.setValue("delegate.rowBounds.offset", RowBounds.NO_ROW_OFFSET);
       metaStatementHandler.setValue("delegate.rowBounds.limit", RowBounds.NO_ROW_LIMIT);
       return invocation.proceed(); 
}
项目:alfresco-repository    文件:PropertyValueDAOImpl.java   
@Override
protected void findPropertiesByIds(List<Long> ids, final PropertyFinderCallback callback)
{
    ResultHandler valueResultHandler = new ResultHandler()
    {
        public void handleResult(ResultContext context)
        {
            PropertyIdQueryResult result = (PropertyIdQueryResult) context.getResultObject();
            Long id = result.getPropId();
            // Make the serializable value
            List<PropertyIdSearchRow> rows = result.getPropValues();
            Serializable value = convertPropertyIdSearchRows(rows);
            callback.handleProperty(id, value);
        }
    };
    // A row handler to roll up individual rows
    Configuration configuration = template.getConfiguration();
    RollupResultHandler rollupResultHandler = new RollupResultHandler(
            configuration,
            KEY_COLUMNS_FINDBYIDS,
            "propValues",
            valueResultHandler);
    // Query using the IDs
    PropertyIdQueryParameter params = new PropertyIdQueryParameter();
    params.setRootPropIds(ids);
    template.select(SELECT_PROPERTIES_BY_IDS, params, rollupResultHandler);
    // Process any remaining results
    rollupResultHandler.processLastResults();
    // Done
}
项目:mumu-core    文件:MapperScanApplication.java   
/**
 * 加载别名
 * @param configuration
 */
private void handleTypeAlias(Configuration configuration, XNode root) {
    log.info("load alias message...........................");
    TypeAliasRegistry typeAliasRegistry = configuration.getTypeAliasRegistry();
    XNode parent = root.evalNode("typeAliases");
    if(parent!=null){
        for (XNode child : parent.getChildren()) {
            if ("package".equals(child.getName())) {
                String typeAliasPackage = child.getStringAttribute("name");
                configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);
                log.info("package:"+typeAliasPackage);
            } else {
                String alias = child.getStringAttribute("alias");
                String type = child.getStringAttribute("type");
                try {
                    Class<?> clazz = Resources.classForName(type);
                    if (alias == null) {
                        typeAliasRegistry.registerAlias(clazz);
                    } else {
                        typeAliasRegistry.registerAlias(alias, clazz);
                    }
                    log.info("alias:"+alias+"   type:"+clazz);
                } catch (ClassNotFoundException e) {
                    throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
                }
            }
        }
    }
}
项目:MybatisGeneatorUtil    文件:MapperTemplate.java   
/**
 * Example-Update中的where结构
 *
 * @param configuration
 * @return
 * @deprecated 4.x版本会移除该方法
 */
@Deprecated
public WhereSqlNode updateByExampleWhereClause(Configuration configuration) {
    //和上面方法的区别就在"example.oredCriteria"
    ForEachSqlNode forEachSqlNode = new ForEachSqlNode(configuration, ExampleValidSqlNode(configuration), "example.oredCriteria", null, "criteria", null, null, " or ");
    WhereSqlNode whereSqlNode = new WhereSqlNode(configuration, forEachSqlNode);
    return whereSqlNode;
}
项目:mybatis-typehandlers-postgis    文件:MultiPointTypeHandlerTest.java   
@BeforeClass
public static void setUp() throws Exception{
    setupSqlSessionFactory("com/eyougo/mybatis/postgis/type/MultiPointTypeHandlerTest.sql");
    Configuration configuration = sqlSessionFactory.getConfiguration();
    configuration.getTypeHandlerRegistry().register(MultiPointTypeHandler.class);
    configuration.addMapper(MultiPointMapper.class);
}
项目:alfresco-core    文件:HierarchicalXMLConfigBuilder.java   
public Configuration parse() {
  if (parsed) {
        throw new BuilderException("Each XMLConfigBuilder can only be used once.");
  }
  parsed = true;
  parseConfiguration(parser.evalNode("/configuration"));
    return configuration;
}
项目:alfresco-core    文件:HierarchicalXMLConfigBuilder.java   
private void settingsElement(XNode context) throws Exception {
    if (context != null) {
        Properties props = context.getChildrenAsProperties();
        // Check that all settings are known to the configuration class
        MetaClass metaConfig = MetaClass.forClass(Configuration.class, localReflectorFactory);
        for (Object key : props.keySet()) {
            if (!metaConfig.hasSetter(String.valueOf(key))) {
                throw new BuilderException("The setting " + key + " is not known.  Make sure you spelled it correctly (case sensitive).");
            }
        }
        configuration.setAutoMappingBehavior(AutoMappingBehavior.valueOf(props.getProperty("autoMappingBehavior", "PARTIAL")));
        configuration.setCacheEnabled(booleanValueOf(props.getProperty("cacheEnabled"), true));
        configuration.setProxyFactory((ProxyFactory) createInstance(props.getProperty("proxyFactory")));
        configuration.setLazyLoadingEnabled(booleanValueOf(props.getProperty("lazyLoadingEnabled"), false));
        configuration.setAggressiveLazyLoading(booleanValueOf(props.getProperty("aggressiveLazyLoading"), true));
        configuration.setMultipleResultSetsEnabled(booleanValueOf(props.getProperty("multipleResultSetsEnabled"), true));
        configuration.setUseColumnLabel(booleanValueOf(props.getProperty("useColumnLabel"), true));
        configuration.setUseGeneratedKeys(booleanValueOf(props.getProperty("useGeneratedKeys"), false));
        configuration.setDefaultExecutorType(ExecutorType.valueOf(props.getProperty("defaultExecutorType", "SIMPLE")));
        configuration.setDefaultStatementTimeout(integerValueOf(props.getProperty("defaultStatementTimeout"), null));
        configuration.setDefaultFetchSize(integerValueOf(props.getProperty("defaultFetchSize"), null));
        configuration.setMapUnderscoreToCamelCase(booleanValueOf(props.getProperty("mapUnderscoreToCamelCase"), false));
        configuration.setSafeRowBoundsEnabled(booleanValueOf(props.getProperty("safeRowBoundsEnabled"), false));
        configuration.setLocalCacheScope(LocalCacheScope.valueOf(props.getProperty("localCacheScope", "SESSION")));
        configuration.setJdbcTypeForNull(JdbcType.valueOf(props.getProperty("jdbcTypeForNull", "OTHER")));
        configuration.setLazyLoadTriggerMethods(stringSetValueOf(props.getProperty("lazyLoadTriggerMethods"), "equals,clone,hashCode,toString"));
        configuration.setSafeResultHandlerEnabled(booleanValueOf(props.getProperty("safeResultHandlerEnabled"), true));
        configuration.setDefaultScriptingLanguage(resolveClass(props.getProperty("defaultScriptingLanguage")));
        configuration.setCallSettersOnNulls(booleanValueOf(props.getProperty("callSettersOnNulls"), false));
        configuration.setLogPrefix(props.getProperty("logPrefix"));
        configuration.setLogImpl(resolveClass(props.getProperty("logImpl")));
    }
}
项目:otus_java_2017_10    文件:MainAnnotationsExample.java   
private SqlSessionFactory getSqlSessionFactory(DataSource dataSource) {
    TransactionFactory transactionFactory = new JdbcTransactionFactory();
    Environment environment = new Environment("development", transactionFactory, dataSource);
    Configuration configuration = new Configuration(environment);

    configuration.addMapper(UsersDAO.class);

    return new SqlSessionFactoryBuilder().build(configuration);
}
项目:alfresco-core    文件:HierarchicalSqlSessionFactoryBeanTest.java   
public void testHierarchyArrayList() throws Exception
{
    Configuration mybatisConfig = getConfiguration(ArrayList.class);
    MappedStatement stmt = mybatisConfig.getMappedStatement(QUERY_ABSTRACTLIST);
    assertNotNull("Query missing for " + QUERY_ABSTRACTLIST + " using " + ArrayList.class, stmt);
    try
    {
        mybatisConfig.getMappedStatement(QUERY_ABSTRACTCOLLECTION);
        fail("Query not missing for " + QUERY_ABSTRACTCOLLECTION + " using " + ArrayList.class);
    }
    catch (IllegalArgumentException e)
    {
        // Expected
    }
}
项目:otus_java_2017_06    文件:MainAnnotationsExample.java   
private SqlSessionFactory getSqlSessionFactory(DataSource dataSource) {
    TransactionFactory transactionFactory = new JdbcTransactionFactory();
    Environment environment = new Environment("development", transactionFactory, dataSource);
    Configuration configuration = new Configuration(environment);

    configuration.addMapper(UsersDAO.class);

    return new SqlSessionFactoryBuilder().build(configuration);
}
项目:tk-mybatis    文件:MapperTemplate.java   
/**
 * Example-Update中的where结构
 *
 * @param configuration
 * @return
 * @deprecated 4.x版本会移除该方法
 */
@Deprecated
public WhereSqlNode updateByExampleWhereClause(Configuration configuration) {
    //和上面方法的区别就在"example.oredCriteria"
    ForEachSqlNode forEachSqlNode = new ForEachSqlNode(configuration, ExampleValidSqlNode(configuration), "example.oredCriteria", null, "criteria", null, null, " or ");
    WhereSqlNode whereSqlNode = new WhereSqlNode(configuration, forEachSqlNode);
    return whereSqlNode;
}