List of usage examples for org.apache.ibatis.session Configuration Configuration
public Configuration()
From source file:org.danielli.xultimate.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. * * @return SqlSessionFactory/* w ww . j a v a 2 s. com*/ * @throws IOException if loading the config file failed */ protected SqlSessionFactory buildSqlSessionFactory() throws IOException { if (this.configuration == null) { this.configuration = new Configuration(); } // Configuration configuration; // XMLConfigBuilder xmlConfigBuilder = null; // if (this.configLocation != null) { // xmlConfigBuilder = new XMLConfigBuilder(this.configLocation.getInputStream(), null, this.configurationProperties); // configuration = xmlConfigBuilder.getConfiguration(); // } else { // if (logger.isDebugEnabled()) { // logger.debug("Property 'configLocation' not specified, using default MyBatis Configuration"); // } // configuration = new Configuration(); // configuration.setVariables(this.configurationProperties); // } if (this.objectFactory != null) { configuration.setObjectFactory(this.objectFactory); } if (this.objectWrapperFactory != null) { configuration.setObjectWrapperFactory(this.objectWrapperFactory); } 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 (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(); } Environment environment = new Environment(this.environment, this.transactionFactory, this.dataSource); configuration.setEnvironment(environment); if (this.databaseIdProvider != null) { try { configuration.setDatabaseId(this.databaseIdProvider.getDatabaseId(this.dataSource)); } catch (SQLException e) { throw new NestedIOException("Failed getting a databaseId", e); } } 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.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/*from ww 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.mybatis.scripting.velocity.InDirectiveTest.java
License:Apache License
@BeforeClass public static void setUpClass() throws Exception { Properties p = new Properties(); p.setProperty("userdirective", InDirective.class.getName()); velocity = new VelocityEngine(); velocity.init(p);// w ww . j a va 2 s . c om ctxt = new VelocityContext(); ctxt.put(SQLScriptSource.MAPPING_COLLECTOR_KEY, new ParameterMappingCollector(new ParameterMapping[] {}, new HashMap<String, Object>(), new Configuration())); StringWriter writer = new StringWriter(); velocity.evaluate(ctxt, writer, "WARM", "1+1"); }
From source file:org.mybatis.spring.batch.builder.MyBatisBatchItemWriterBuilderTest.java
License:Apache License
@BeforeEach void setUp() {/*from w w w . ja v a 2 s. c o m*/ MockitoAnnotations.initMocks(this); { Configuration configuration = new Configuration(); Environment environment = new Environment("unittest", new JdbcTransactionFactory(), dataSource); configuration.setEnvironment(environment); Mockito.when(this.sqlSessionFactory.getConfiguration()).thenReturn(configuration); Mockito.when(this.sqlSessionFactory.openSession(ExecutorType.BATCH)).thenReturn(this.sqlSession); } { BatchResult result = new BatchResult(null, null); result.setUpdateCounts(new int[] { 1 }); Mockito.when(this.sqlSession.flushStatements()).thenReturn(Collections.singletonList(result)); } }
From source file:org.mybatis.spring.batch.builder.MyBatisPagingItemReaderBuilderTest.java
License:Apache License
@BeforeEach void setUp() {// ww w. j a va 2s . co m MockitoAnnotations.initMocks(this); Configuration configuration = new Configuration(); Environment environment = new Environment("unittest", new JdbcTransactionFactory(), dataSource); configuration.setEnvironment(environment); Mockito.when(this.sqlSessionFactory.getConfiguration()).thenReturn(configuration); Mockito.when(this.sqlSessionFactory.openSession(ExecutorType.BATCH)).thenReturn(this.sqlSession); Map<String, Object> parameters = new HashMap<>(); parameters.put("id", 1); parameters.put("_page", 0); parameters.put("_pagesize", 10); parameters.put("_skiprows", 0); Mockito.when(this.sqlSession.selectList("selectFoo", parameters)).thenReturn(getFoos()); }
From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java
License:Apache License
@Test void testCustomThymeleafConfig() { this.context.register(ThymeleafCustomLanguageDriverConfig.class, MybatisLanguageDriverAutoConfiguration.class); this.context.refresh(); ThymeleafLanguageDriver driver = this.context.getBean(ThymeleafLanguageDriver.class); SqlSource sqlSource = driver.createSqlSource(new Configuration(), "SELECT * FROM users WHERE id = /*[# m:p='id']*/ 1 /*[/]*/", Integer.class); BoundSql boundSql = sqlSource.getBoundSql(10); assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ?"); assertThat(boundSql.getParameterObject()).isEqualTo(10); assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); ThymeleafLanguageDriverConfig config = this.context.getBean(ThymeleafLanguageDriverConfig.class); assertThat(config.isUse2way()).isEqualTo(true); assertThat(config.getDialect().getPrefix()).isEqualTo("m"); assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).isNull(); assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('\\'); assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("ESCAPE '%s'"); assertThat(config.getTemplateFile().getBaseDir()).isEqualTo(""); assertThat(config.getTemplateFile().getCacheTtl()).isNull(); assertThat(config.getTemplateFile().getEncoding()).isEqualTo(StandardCharsets.UTF_8); assertThat(config.getTemplateFile().getPatterns()).hasSize(1).contains("*.sql"); assertThat(config.getCustomizer()).isNull(); }
From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java
License:Apache License
@Test void testCustomFreeMarkerConfig() { this.context.register(FreeMarkerCustomLanguageDriverConfig.class, MybatisLanguageDriverAutoConfiguration.class); this.context.refresh(); FreeMarkerLanguageDriver driver = this.context.getBean(FreeMarkerLanguageDriver.class); @SuppressWarnings("unused") class Param { private Integer id; private Integer version; }//from ww w . jav a 2 s. com Param params = new Param(); params.id = 10; params.version = 20; SqlSource sqlSource = driver.createSqlSource(new Configuration(), "SELECT * FROM users WHERE id = #{id} and version = <@p name='version'/>", Param.class); BoundSql boundSql = sqlSource.getBoundSql(params); assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ? and version = ?"); assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); assertThat(boundSql.getParameterMappings().get(1).getProperty()).isEqualTo("version"); assertThat(boundSql.getParameterMappings().get(1).getJavaType()).isEqualTo(Integer.class); FreeMarkerLanguageDriverConfig config = this.context.getBean(FreeMarkerLanguageDriverConfig.class); assertThat(config.getBasePackage()).isEqualTo(""); assertThat(config.getFreemarkerSettings()).hasSize(1); assertThat(config.getFreemarkerSettings().get("interpolation_syntax")).isEqualTo("dollar"); }
From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java
License:Apache License
@Test void testCustomVelocityConfig() { this.context.register(VelocityCustomLanguageDriverConfig.class, MybatisLanguageDriverAutoConfiguration.class); this.context.refresh(); VelocityLanguageDriver driver = this.context.getBean(VelocityLanguageDriver.class); @SuppressWarnings("unused") class Param { private Integer id; private Integer version; }/*from w w w. jav a2s .com*/ Param params = new Param(); params.id = 10; params.version = 20; SqlSource sqlSource = driver.createSqlSource(new Configuration(), "#now()", Param.class); BoundSql boundSql = sqlSource.getBoundSql(params); assertThat(boundSql.getSql()).isEqualTo("SELECT CURRENT_TIMESTAMP"); VelocityLanguageDriverConfig config = this.context.getBean(VelocityLanguageDriverConfig.class); @SuppressWarnings("deprecation") String[] userDirective = config.getUserdirective(); assertThat(userDirective).hasSize(0); assertThat(config.getAdditionalContextAttributes()).hasSize(0); assertThat(config.getVelocitySettings()).hasSize(3); assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADERS)).isEqualTo("class"); assertThat(config.getVelocitySettings().get(RuntimeConstants.RESOURCE_LOADER + ".class.class")) .isEqualTo("org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); assertThat(config.generateCustomDirectivesString()).isEqualTo(NowDirective.class.getName() + ",org.mybatis.scripting.velocity.TrimDirective,org.mybatis.scripting.velocity.WhereDirective,org.mybatis.scripting.velocity.SetDirective,org.mybatis.scripting.velocity.InDirective,org.mybatis.scripting.velocity.RepeatDirective"); }
From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java
License:Apache License
@Test void testCustomThymeleafConfigUsingConfigurationProperty() { TestPropertyValues.of("mybatis.scripting-language-driver.thymeleaf.use2way=false", "mybatis.scripting-language-driver.thymeleaf.dialect.like-additional-escape-target-chars=*,?", "mybatis.scripting-language-driver.thymeleaf.dialect.like-escape-char=~", "mybatis.scripting-language-driver.thymeleaf.dialect.like-escape-clause-format=escape '%s'", "mybatis.scripting-language-driver.thymeleaf.dialect.prefix=mybatis", "mybatis.scripting-language-driver.thymeleaf.template-file.base-dir=sqls", "mybatis.scripting-language-driver.thymeleaf.template-file.cache-enabled=false", "mybatis.scripting-language-driver.thymeleaf.template-file.cache-ttl=1234", "mybatis.scripting-language-driver.thymeleaf.template-file.encoding=Windows-31J", "mybatis.scripting-language-driver.thymeleaf.template-file.patterns=*.sql,*.sqlf", "mybatis.scripting-language-driver.thymeleaf.customizer=org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest$MyTemplateEngineCustomizer") .applyTo(this.context); this.context.register(MyAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class); this.context.refresh(); ThymeleafLanguageDriver driver = this.context.getBean(ThymeleafLanguageDriver.class); SqlSource sqlSource = driver.createSqlSource(new Configuration(), "SELECT * FROM users WHERE id = [# mybatis:p='id' /]", Integer.class); BoundSql boundSql = sqlSource.getBoundSql(10); assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ?"); assertThat(boundSql.getParameterObject()).isEqualTo(10); assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); ThymeleafLanguageDriverConfig config = this.context.getBean(ThymeleafLanguageDriverConfig.class); assertThat(config.isUse2way()).isEqualTo(false); assertThat(config.getDialect().getPrefix()).isEqualTo("mybatis"); assertThat(config.getDialect().getLikeAdditionalEscapeTargetChars()).hasSize(2).contains('*', '?'); assertThat(config.getDialect().getLikeEscapeChar()).isEqualTo('~'); assertThat(config.getDialect().getLikeEscapeClauseFormat()).isEqualTo("escape '%s'"); assertThat(config.getTemplateFile().getBaseDir()).isEqualTo("sqls"); assertThat(config.getTemplateFile().getCacheTtl()).isEqualTo(1234); assertThat(config.getTemplateFile().getEncoding()).isEqualTo(Charset.forName("Windows-31J")); assertThat(config.getTemplateFile().getPatterns()).hasSize(2).contains("*.sql", "*.sqlf"); assertThat(config.getCustomizer()).isEqualTo(MyTemplateEngineCustomizer.class); }
From source file:org.mybatis.spring.boot.autoconfigure.MybatisLanguageDriverAutoConfigurationTest.java
License:Apache License
@Test void testCustomFreeMarkerConfigUsingConfigurationProperty() { TestPropertyValues.of("mybatis.scripting-language-driver.freemarker.base-package=sqls", "mybatis.scripting-language-driver.freemarker.freemarker-settings.interpolation_syntax=dollar", "mybatis.scripting-language-driver.freemarker.freemarker-settings.whitespace_stripping=yes") .applyTo(this.context); this.context.register(MyAutoConfiguration.class, MybatisLanguageDriverAutoConfiguration.class); this.context.refresh(); FreeMarkerLanguageDriver driver = this.context.getBean(FreeMarkerLanguageDriver.class); @SuppressWarnings("unused") class Param { private Integer id; private Integer version; }//from w w w. jav a2s . com Param params = new Param(); params.id = 10; params.version = 20; SqlSource sqlSource = driver.createSqlSource(new Configuration(), "SELECT * FROM users WHERE id = #{id} and version = <@p name='version'/>", Param.class); BoundSql boundSql = sqlSource.getBoundSql(params); assertThat(boundSql.getSql()).isEqualTo("SELECT * FROM users WHERE id = ? and version = ?"); assertThat(boundSql.getParameterMappings().get(0).getProperty()).isEqualTo("id"); assertThat(boundSql.getParameterMappings().get(0).getJavaType()).isEqualTo(Integer.class); assertThat(boundSql.getParameterMappings().get(1).getProperty()).isEqualTo("version"); assertThat(boundSql.getParameterMappings().get(1).getJavaType()).isEqualTo(Integer.class); FreeMarkerLanguageDriverConfig config = this.context.getBean(FreeMarkerLanguageDriverConfig.class); assertThat(config.getBasePackage()).isEqualTo("sqls"); assertThat(config.getFreemarkerSettings()).hasSize(2); assertThat(config.getFreemarkerSettings().get("interpolation_syntax")).isEqualTo("dollar"); assertThat(config.getFreemarkerSettings().get("whitespace_stripping")).isEqualTo("yes"); }