List of usage examples for org.apache.ibatis.session Configuration getVariables
public Properties getVariables()
From source file:com.zyf.framework.plugin.SqlSessionFactoryBean.java
License:Apache License
/** * Build a {@code SqlSessionFactory} instance. * * The default implementation uses the standard MyBatis {@code XMLConfigBuilder} API to build a * {@code SqlSessionFactory} instance based on an Reader. * Since 1.3.0, it can be specified a {@link Configuration} instance directly(without config file). * * @return SqlSessionFactory/*from w w w . j a va 2 s . co m*/ * @throws IOException if loading the config file failed */ protected SqlSessionFactory buildSqlSessionFactory() throws IOException { Configuration configuration; XMLConfigBuilder xmlConfigBuilder = null; if (this.configuration != null) { configuration = this.configuration; if (configuration.getVariables() == null) { configuration.setVariables(this.configurationProperties); } else if (this.configurationProperties != null) { configuration.getVariables().putAll(this.configurationProperties); } } else if (this.configLocation != null) { xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties); configuration = xmlConfigBuilder.getConfiguration(); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration"); } configuration = new Configuration(); if (this.configurationProperties != null) { configuration.setVariables(this.configurationProperties); } } if (this.objectFactory != null) { configuration.setObjectFactory(this.objectFactory); } if (this.objectWrapperFactory != null) { configuration.setObjectWrapperFactory(this.objectWrapperFactory); } if (this.vfs != null) { configuration.setVfsImpl(this.vfs); } if (hasLength(this.typeAliasesPackage)) { String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeAliasPackageArray) { configuration.getTypeAliasRegistry().registerAliases(packageToScan, typeAliasesSuperType == null ? Object.class : typeAliasesSuperType); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases"); } } } if (!isEmpty(this.typeAliases)) { for (Class<?> typeAlias : this.typeAliases) { configuration.getTypeAliasRegistry().registerAlias(typeAlias); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registered type alias: '" + typeAlias + "'"); } } } if (!isEmpty(this.plugins)) { for (Interceptor plugin : this.plugins) { configuration.addInterceptor(plugin); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registered plugin: '" + plugin + "'"); } } } if (hasLength(this.typeHandlersPackage)) { String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeHandlersPackageArray) { configuration.getTypeHandlerRegistry().register(packageToScan); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Scanned package: '" + packageToScan + "' for type handlers"); } } } if (!isEmpty(this.typeHandlers)) { for (TypeHandler<?> typeHandler : this.typeHandlers) { //TODO: ClazzTypeScan cts = typeHandler.getClass().getAnnotation(ClazzTypeScan.class); if (cts == null) { configuration.getTypeHandlerRegistry().register(typeHandler); } else { TypeScan typescan = cts.value(); if (typeScanMap.containsKey(typescan.name())) { String scanpath = typeScanMap.get(typescan.name()); ResolverUtil<Class<?>> resolverUtil = new ResolverUtil<>(); resolverUtil.find(new ResolverUtil.IsA(DescriptionID.class), scanpath); Set<Class<? extends Class<?>>> handlerSet = resolverUtil.getClasses(); for (Class<?> type : handlerSet) { try { Constructor<?> c = typeHandler.getClass().getConstructor(Class.class); c.newInstance(type); } catch (NoSuchMethodException | SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (!type.isAnonymousClass() && !type.isInterface() && !Modifier.isAbstract(type.getModifiers())) { configuration.getTypeHandlerRegistry().register(type, typeHandler.getClass()); } } } } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registered type handler: '" + typeHandler + "'"); } } } if (this.databaseIdProvider != null) {//fix #64 set databaseId before parse mapper xmls try { configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource)); } catch (SQLException e) { throw new NestedIOException("Failed getting a databaseId", e); } } if (this.cache != null) { configuration.addCache(this.cache); } if (xmlConfigBuilder != null) { try { xmlConfigBuilder.parse(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parsed configuration file: '" + this.configLocation + "'"); } } catch (Exception ex) { throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex); } finally { ErrorContext.instance().reset(); } } if (this.transactionFactory == null) { this.transactionFactory = new SpringManagedTransactionFactory(); } configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource)); if (!isEmpty(this.mapperLocations)) { for (Resource mapperLocation : this.mapperLocations) { if (mapperLocation == null) { continue; } try { XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); } catch (Exception e) { throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e); } finally { ErrorContext.instance().reset(); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'"); } } // ThinkGem ?MapperXML? if (mapperRefresh.isEnabled()) { System.out.println("mapperRefresh loading............."); mapperRefresh.setConfiguration(configuration); mapperRefresh.setMapperLocations(mapperLocations); mapperRefresh.run(); } } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found"); } } return this.sqlSessionFactoryBuilder.build(configuration); }
From source file:das.orm.ORMBackendConnector.java
License:Apache License
public ORMBackendConnector(String configURI, Connection conn) throws IOException, PersistenceException { log.trace(">>> constructor"); if ((configURI == null) || configURI.length() == 0) { //String fs = System.getProperty("file.separator"); // ? ? ?? String fs = "/"; configURI = getClass().getPackage().getName().replace(".", fs).concat(fs).concat("orm-config.xml"); }/*from ww w .j av a 2 s .c o m*/ log.debug("configURI=" + configURI); InputStream config = Resources.getResourceAsStream(configURI); log.debug("config ready"); this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(config); log.debug("SqlSessionFactoryBuilder created"); connection = conn; if (conn != null) { this.keepDBConnection = true; } else { Configuration conf = getConfiguration(); Properties props = conf.getVariables(); // ? ? "" ??. // ? ? ? ? ? SqlSession // ?? ?, ? , // ? ? - ? ?, // . // ? , ? ? ? String prop = props.getProperty("keepDBConnection", "false"); this.keepDBConnection = Boolean.parseBoolean(prop); } log.debug("keepDBConnection=" + keepDBConnection); }
From source file:ee.ut.cs.mc.and.activiti521.custom.ibatis.NonValidatingXMLMapperBuilder.java
License:Apache License
public NonValidatingXMLMapperBuilder(InputStream inputStream, Configuration configuration, String resource, Map<String, XNode> sqlFragments) { //TODO Android doesnt support a validating XPathParser this(new XPathParser(inputStream, false, configuration.getVariables(), new XMLMapperEntityResolver()), configuration, resource, sqlFragments); }
From source file:org.fastcatsearch.analytics.db.CommonDBHandler.java
License:Open Source License
public boolean load() { if (driverProperties == null) { driverProperties = new Properties(); }//from ww w.j a v a2s . c o m String dbType = settings.getString("type"); driverProperties.setProperty("user", settings.getString("user")); driverProperties.setProperty("password", settings.getString("password")); driverProperties.setProperty("driver.encoding", "UTF-8"); boolean isAutoCommit = settings.getBoolean("autocommit", true); boolean usePooling = settings.getBoolean("usePooling", true); DataSource dataSource = null; if (usePooling) { PooledDataSource pooledDataSource = new PooledDataSource(settings.getString("driver"), settings.getString("url"), driverProperties); boolean poolPingEnabled = settings.getBoolean("poolPingEnabled", true); String poolPingQuery = settings.getString("poolPingQuery"); int poolPingConnectionsNotUsedFor = settings.getInt("poolPingConnectionsNotUsedFor", -1); int poolTimeToWait = settings.getInt("poolTimeToWait", -1); int poolMaximumActiveConnections = settings.getInt("poolMaximumActiveConnections", -1); int poolMaximumIdleConnections = settings.getInt("poolMaximumIdleConnections", -1); pooledDataSource.setPoolPingEnabled(poolPingEnabled); if (poolPingQuery != null) { pooledDataSource.setPoolPingQuery(poolPingQuery); } if (poolPingConnectionsNotUsedFor != -1) { pooledDataSource.setPoolPingConnectionsNotUsedFor(poolPingConnectionsNotUsedFor); } if (poolTimeToWait != -1) { pooledDataSource.setPoolTimeToWait(poolTimeToWait); } if (poolMaximumActiveConnections != -1) { pooledDataSource.setPoolMaximumActiveConnections(poolMaximumActiveConnections); } if (poolMaximumIdleConnections != -1) { pooledDataSource.setPoolMaximumIdleConnections(poolMaximumIdleConnections); } //autocommit pooledDataSource.setDefaultAutoCommit(isAutoCommit); dataSource = pooledDataSource; } else { UnpooledDataSource unpooledDataSource = new UnpooledDataSource(settings.getString("driver"), settings.getString("url"), driverProperties); unpooledDataSource.setAutoCommit(isAutoCommit); dataSource = unpooledDataSource; } org.apache.ibatis.mapping.Environment environment = new org.apache.ibatis.mapping.Environment("ID", new JdbcTransactionFactory(), dataSource); Configuration configuration = new Configuration(environment); if (globalParam != null) { configuration.getVariables().putAll(globalParam); } if (mapperList != null) { List<URL> mapperFileList = new ArrayList<URL>(); for (Class<?> mapperDAO : mapperList) { try { String mapperFilePath = mapperDAO.getName().replace('.', '/') + "_" + dbType + ".xml"; URL mapperFile = Resources.getResourceURL(mapperFilePath); mapperFileList.add(mapperFile); } catch (IOException e) { logger.error("error load MapperFile", e); } } for (URL mapperFile : mapperFileList) { addSqlMappings(configuration, mapperFile); } } sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration); return true; }
From source file:org.lucius.iyanla.orm.mybatis.SqlSessionFactoryBean.java
License:Apache License
/** * Build a {@code SqlSessionFactory} instance. * * The default implementation uses the standard MyBatis * {@code XMLConfigBuilder} API to build a {@code SqlSessionFactory} * instance based on an Reader. Since 1.3.0, it can be specified a * {@link Configuration} instance directly(without config file). * * @return SqlSessionFactory// w w w . j a va 2 s . c o m * @throws IOException * if loading the config file failed */ protected SqlSessionFactory buildSqlSessionFactory() throws IOException { Configuration configuration; XMLConfigBuilder xmlConfigBuilder = null; if (this.configuration != null) { configuration = this.configuration; if (configuration.getVariables() == null) { configuration.setVariables(this.configurationProperties); } else if (this.configurationProperties != null) { configuration.getVariables().putAll(this.configurationProperties); } } else if (this.configLocation != null) { xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties); configuration = xmlConfigBuilder.getConfiguration(); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug( "Property 'configuration' or 'configLocation' not specified, using default MyBatis Configuration"); } configuration = new Configuration(); if (this.configurationProperties != null) { configuration.setVariables(this.configurationProperties); } } if (this.objectFactory != null) { configuration.setObjectFactory(this.objectFactory); } if (this.objectWrapperFactory != null) { configuration.setObjectWrapperFactory(this.objectWrapperFactory); } if (this.vfs != null) { configuration.setVfsImpl(this.vfs); } if (hasLength(this.typeAliasesPackage)) { String[] typeAliasPackageArray = tokenizeToStringArray(this.typeAliasesPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeAliasPackageArray) { configuration.getTypeAliasRegistry().registerAliases(packageToScan, typeAliasesSuperType == null ? Object.class : typeAliasesSuperType); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Scanned package: '" + packageToScan + "' for aliases"); } } } if (!isEmpty(this.typeAliases)) { for (Class<?> typeAlias : this.typeAliases) { configuration.getTypeAliasRegistry().registerAlias(typeAlias); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registered type alias: '" + typeAlias + "'"); } } } if (!isEmpty(this.plugins)) { for (Interceptor plugin : this.plugins) { configuration.addInterceptor(plugin); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registered plugin: '" + plugin + "'"); } } } if (hasLength(this.typeHandlersPackage)) { String[] typeHandlersPackageArray = tokenizeToStringArray(this.typeHandlersPackage, ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS); for (String packageToScan : typeHandlersPackageArray) { configuration.getTypeHandlerRegistry().register(packageToScan); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Scanned package: '" + packageToScan + "' for type handlers"); } } } if (!isEmpty(this.typeHandlers)) { for (TypeHandler<?> typeHandler : this.typeHandlers) { configuration.getTypeHandlerRegistry().register(typeHandler); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Registered type handler: '" + typeHandler + "'"); } } } if (this.databaseIdProvider != null) {// fix #64 set databaseId before // parse mapper xmls try { configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource)); } catch (SQLException e) { throw new NestedIOException("Failed getting a databaseId", e); } } if (this.cache != null) { configuration.addCache(this.cache); } if (xmlConfigBuilder != null) { try { xmlConfigBuilder.parse(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parsed configuration file: '" + this.configLocation + "'"); } } catch (Exception ex) { throw new NestedIOException("Failed to parse config resource: " + this.configLocation, ex); } finally { ErrorContext.instance().reset(); } } if (this.transactionFactory == null) { this.transactionFactory = new SpringManagedTransactionFactory(); } configuration.setEnvironment(new Environment(this.environment, this.transactionFactory, this.dataSource)); // ?bundleMapper this.mapperLocations = getMapperLocations(); if (!isEmpty(this.mapperLocations)) { for (Resource mapperLocation : this.mapperLocations) { if (mapperLocation == null) { continue; } try { XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(mapperLocation.getInputStream(), configuration, mapperLocation.toString(), configuration.getSqlFragments()); xmlMapperBuilder.parse(); } catch (Exception e) { throw new NestedIOException("Failed to parse mapping resource: '" + mapperLocation + "'", e); } finally { ErrorContext.instance().reset(); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Parsed mapper file: '" + mapperLocation + "'"); } } } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Property 'mapperLocations' was not specified or no matching resources found"); } } return this.sqlSessionFactoryBuilder.build(configuration); }
From source file:org.sonar.core.persistence.MyBatis.java
License:Open Source License
public MyBatis start() { LogFactory.useSlf4jLogging();//from w ww . j av a 2 s . c o m Configuration conf = new Configuration(); conf.setEnvironment(new Environment("production", createTransactionFactory(), database.getDataSource())); conf.setUseGeneratedKeys(true); conf.setLazyLoadingEnabled(false); conf.setJdbcTypeForNull(JdbcType.NULL); Dialect dialect = database.getDialect(); conf.setDatabaseId(dialect.getId()); conf.getVariables().setProperty("_true", dialect.getTrueSqlValue()); conf.getVariables().setProperty("_false", dialect.getFalseSqlValue()); conf.getVariables().setProperty("_scrollFetchSize", String.valueOf(dialect.getScrollDefaultFetchSize())); loadAlias(conf, "ActiveDashboard", ActiveDashboardDto.class); loadAlias(conf, "Author", AuthorDto.class); loadAlias(conf, "Component", ComponentDto.class); loadAlias(conf, "Dashboard", DashboardDto.class); loadAlias(conf, "Dependency", DependencyDto.class); loadAlias(conf, "DuplicationUnit", DuplicationUnitDto.class); loadAlias(conf, "Graph", GraphDto.class); loadAlias(conf, "Group", GroupDto.class); loadAlias(conf, "GroupRole", GroupRoleDto.class); loadAlias(conf, "GroupMembership", GroupMembershipDto.class); loadAlias(conf, "LoadedTemplate", LoadedTemplateDto.class); loadAlias(conf, "MeasureFilter", MeasureFilterDto.class); loadAlias(conf, "NotificationQueue", NotificationQueueDto.class); loadAlias(conf, "Property", PropertyDto.class); loadAlias(conf, "PurgeableSnapshot", PurgeableSnapshotDto.class); loadAlias(conf, "QualityGate", QualityGateDto.class); loadAlias(conf, "QualityGateCondition", QualityGateConditionDto.class); loadAlias(conf, "ProjectQgateAssociation", ProjectQgateAssociationDto.class); loadAlias(conf, "Resource", ResourceDto.class); loadAlias(conf, "ResourceIndex", ResourceIndexDto.class); loadAlias(conf, "ResourceSnapshot", ResourceSnapshotDto.class); loadAlias(conf, "Rule", RuleDto.class); loadAlias(conf, "RuleParam", RuleParamDto.class); loadAlias(conf, "Snapshot", SnapshotDto.class); loadAlias(conf, "Semaphore", SemaphoreDto.class); loadAlias(conf, "SchemaMigration", SchemaMigrationDto.class); loadAlias(conf, "User", UserDto.class); loadAlias(conf, "UserRole", UserRoleDto.class); loadAlias(conf, "Widget", WidgetDto.class); loadAlias(conf, "WidgetProperty", WidgetPropertyDto.class); loadAlias(conf, "MeasureModel", MeasureModel.class); loadAlias(conf, "Measure", MeasureDto.class); loadAlias(conf, "Metric", MetricDto.class); loadAlias(conf, "Issue", IssueDto.class); loadAlias(conf, "IssueChange", IssueChangeDto.class); loadAlias(conf, "IssueFilter", IssueFilterDto.class); loadAlias(conf, "IssueFilterFavourite", IssueFilterFavouriteDto.class); loadAlias(conf, "SnapshotData", SnapshotDataDto.class); loadAlias(conf, "ActionPlanIssue", ActionPlanDto.class); loadAlias(conf, "ActionPlanStats", ActionPlanStatsDto.class); loadAlias(conf, "PermissionTemplate", PermissionTemplateDto.class); loadAlias(conf, "PermissionTemplateUser", PermissionTemplateUserDto.class); loadAlias(conf, "PermissionTemplateGroup", PermissionTemplateGroupDto.class); loadAlias(conf, "Characteristic", CharacteristicDto.class); loadAlias(conf, "UserWithPermission", UserWithPermissionDto.class); loadAlias(conf, "GroupWithPermission", GroupWithPermissionDto.class); loadAlias(conf, "QualityProfile", QualityProfileDto.class); loadAlias(conf, "ActiveRule", ActiveRuleDto.class); loadAlias(conf, "ActiveRuleParam", ActiveRuleParamDto.class); loadAlias(conf, "RequirementMigration", RequirementMigrationDto.class); loadAlias(conf, "Activity", ActivityDto.class); loadAlias(conf, "AnalysisReport", AnalysisReportDto.class); loadAlias(conf, "IdUuidPair", IdUuidPair.class); // AuthorizationMapper has to be loaded before IssueMapper because this last one used it loadMapper(conf, "org.sonar.core.user.AuthorizationMapper"); // ResourceMapper has to be loaded before IssueMapper because this last one used it loadMapper(conf, ResourceMapper.class); loadMapper(conf, "org.sonar.core.permission.PermissionMapper"); Class<?>[] mappers = { ActivityMapper.class, ActiveDashboardMapper.class, AuthorMapper.class, DashboardMapper.class, DependencyMapper.class, DuplicationMapper.class, GraphDtoMapper.class, IssueMapper.class, IssueChangeMapper.class, IssueFilterMapper.class, IssueFilterFavouriteMapper.class, LoadedTemplateMapper.class, MeasureFilterMapper.class, Migration44Mapper.class, PermissionTemplateMapper.class, PropertiesMapper.class, PurgeMapper.class, ResourceKeyUpdaterMapper.class, ResourceIndexerMapper.class, ResourceSnapshotMapper.class, RoleMapper.class, RuleMapper.class, SchemaMigrationMapper.class, SemaphoreMapper.class, UserMapper.class, GroupMapper.class, WidgetMapper.class, WidgetPropertyMapper.class, org.sonar.api.database.model.MeasureMapper.class, SnapshotDataMapper.class, FileSourceMapper.class, ActionPlanMapper.class, ActionPlanStatsMapper.class, NotificationQueueMapper.class, CharacteristicMapper.class, GroupMembershipMapper.class, QualityProfileMapper.class, ActiveRuleMapper.class, MeasureMapper.class, MetricMapper.class, QualityGateMapper.class, QualityGateConditionMapper.class, ComponentMapper.class, SnapshotMapper.class, ProjectQgateAssociationMapper.class, AnalysisReportMapper.class, Migration45Mapper.class, Migration50Mapper.class }; loadMappers(conf, mappers); configureLogback(mappers); sessionFactory = new SqlSessionFactoryBuilder().build(conf); return this; }