Java Code Examples for org.apache.ibatis.session.Configuration#getSqlFragments()

The following examples show how to use org.apache.ibatis.session.Configuration#getSqlFragments() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SqlSessionMapperHotspotLoader.java    From super-cloudops with Apache License 2.0 6 votes vote down vote up
/**
 * Refresh the contents of mybatis mapping files.
 * 
 * @param configuration
 * @throws Exception
 */
private synchronized void refresh(Configuration configuration) throws Exception {
	// 清理Mybatis的所有映射文件缓存, 目前由于未找到清空被修改文件的缓存的key值, 暂时仅支持全部清理, 然后全部加载
	doCleanupOlderCacheConfig(configuration);

	long begin = currentTimeMillis();
	for (Resource rs : mapperLocations) {
		try {
			XMLMapperBuilder builder = new XMLMapperBuilder(rs.getInputStream(), configuration, rs.toString(),
					configuration.getSqlFragments()); // Reload.
			builder.parse();
			log.debug("Refreshed for: {}", rs);
		} catch (IOException e) {
			log.error(format("Failed to refresh mapper for: %s", rs), e);
		}
	}
	long now = currentTimeMillis();
	out.println(format("%s - Refreshed mappers: %s, cost: %sms", new Date(), mapperLocations.length, (now - begin)));

	// Update refresh time.
	lastRefreshTime.set(now);
}
 
Example 2
Source File: SqlSessionFactoryBean.java    From Shop-for-JavaWeb with MIT License 6 votes vote down vote up
/**
 * TODO 刷新
 * 
 * @param inputStream
 * @param resource
 * @param configuration
 * @throws NestedIOException
 */
public static void refresh(java.io.InputStream inputStream,
		String resource, Configuration configuration)
		throws NestedIOException {

	try {
		XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(
				inputStream, configuration, resource,
				configuration.getSqlFragments());
		xmlMapperBuilder.parse1();
	} catch (Exception e) {
		throw new NestedIOException("Failed to parse mapping resource: '"
				+ resource + "'", e);
	} finally {
		ErrorContext.instance().reset();
	}

}
 
Example 3
Source File: MybatisHelper.java    From snakerflow with Apache License 2.0 6 votes vote down vote up
/**
 * 使用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);
}
 
Example 4
Source File: MybatisXmlProcess.java    From springboot-plugin-framework-parent with Apache License 2.0 5 votes vote down vote up
/**
 * 加载xml资源
 * @param resources resources
 * @param pluginClassLoader pluginClassLoader
 * @throws Exception Exception
 */
public void loadXmlResource(List<Resource> resources, ClassLoader pluginClassLoader) throws Exception {
    if(resources == null || resources.isEmpty()){
        return;
    }
    Configuration configuration = factory.getConfiguration();
    // removeConfig(configuration);
    ClassLoader defaultClassLoader = Resources.getDefaultClassLoader();
    try {
        Resources.setDefaultClassLoader(pluginClassLoader);
        for (Resource resource :resources) {
            InputStream inputStream = resource.getInputStream();
            try {
                PluginMybatisXmlMapperBuilder xmlMapperBuilder =  new PluginMybatisXmlMapperBuilder(
                        inputStream,
                        configuration, resource.toString(),
                        configuration.getSqlFragments(),
                        pluginClassLoader);
                xmlMapperBuilder.parse();
            } finally {
                if(inputStream != null){
                    inputStream.close();
                }
            }

        }
    } finally {
        ErrorContext.instance().reset();
        Resources.setDefaultClassLoader(defaultClassLoader);
    }
}
 
Example 5
Source File: ResultMapTest.java    From mybatis-test with Apache License 2.0 5 votes vote down vote up
@Test
public void printResultMapInfo() throws Exception {
    Configuration configuration = new Configuration();
    String resource = "chapter3/mapper/ArticleMapper.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    XMLMapperBuilder builder = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
    builder.parse();

    ResultMap resultMap = configuration.getResultMap("articleResult");

    System.out.println("\n-------------------+✨ mappedColumns ✨+--------------------");
    System.out.println(resultMap.getMappedColumns());

    System.out.println("\n------------------+✨ mappedProperties ✨+------------------");
    System.out.println(resultMap.getMappedProperties());

    System.out.println("\n------------------+✨ idResultMappings ✨+------------------");
    resultMap.getIdResultMappings().forEach(rm -> System.out.println(simplify(rm)));

    System.out.println("\n---------------+✨ propertyResultMappings ✨+---------------");
    resultMap.getPropertyResultMappings().forEach(rm -> System.out.println(simplify(rm)));

    System.out.println("\n-------------+✨ constructorResultMappings ✨+--------------");
    resultMap.getConstructorResultMappings().forEach(rm -> System.out.println(simplify(rm)));

    System.out.println("\n------------------+✨ resultMappings ✨+--------------------");
    resultMap.getResultMappings().forEach(rm -> System.out.println(simplify(rm)));

    System.out.println();
    inputStream.close();
}
 
Example 6
Source File: FormEngineConfiguration.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public Configuration parseCustomMybatisXMLMappers(Configuration configuration) {
  if (getCustomMybatisXMLMappers() != null)
    // see XMLConfigBuilder.mapperElement()
    for (String resource : getCustomMybatisXMLMappers()) {
    XMLMapperBuilder mapperParser = new XMLMapperBuilder(getResourceAsStream(resource), configuration, resource, configuration.getSqlFragments());
    mapperParser.parse();
    }
  return configuration;
}
 
Example 7
Source File: ProcessEngineConfigurationImpl.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected Configuration parseCustomMybatisXMLMappers(Configuration configuration) {
 if (getCustomMybatisXMLMappers() != null)
  // see XMLConfigBuilder.mapperElement()
  for(String resource: getCustomMybatisXMLMappers()){
    XMLMapperBuilder mapperParser = new XMLMapperBuilder(getResourceAsStream(resource), 
        configuration, resource, configuration.getSqlFragments());
    mapperParser.parse();
  }
  return configuration;
}
 
Example 8
Source File: ProcessEngineConfigurationImpl.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public Configuration parseCustomMybatisXMLMappers(Configuration configuration) {
  if (getCustomMybatisXMLMappers() != null)
    // see XMLConfigBuilder.mapperElement()
    for (String resource : getCustomMybatisXMLMappers()) {
      XMLMapperBuilder mapperParser = new XMLMapperBuilder(getResourceAsStream(resource), configuration, resource, configuration.getSqlFragments());
      mapperParser.parse();
    }
  return configuration;
}
 
Example 9
Source File: DmnEngineConfiguration.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
public Configuration parseCustomMybatisXMLMappers(Configuration configuration) {
  if (getCustomMybatisXMLMappers() != null)
    // see XMLConfigBuilder.mapperElement()
    for (String resource : getCustomMybatisXMLMappers()) {
    XMLMapperBuilder mapperParser = new XMLMapperBuilder(getResourceAsStream(resource), configuration, resource, configuration.getSqlFragments());
    mapperParser.parse();
    }
  return configuration;
}
 
Example 10
Source File: MapperLoader.java    From Shop-for-JavaWeb with MIT License 5 votes vote down vote up
public void reloadXML() throws Exception {
	SqlSessionFactory factory = context.getBean(SqlSessionFactory.class);
	Configuration configuration = factory.getConfiguration();
	// 移除加载项
	removeConfig(configuration);
	// 重新扫描加载
	for (String basePackage : basePackages) {
		Resource[] resources = getResource(basePackage, XML_RESOURCE_PATTERN);
		if (resources != null) {
			for (int i = 0; i < resources.length; i++) {
				if (resources[i] == null) {
					continue;
				}
				try {
					XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(resources[i].getInputStream(),
							configuration, resources[i].toString(), configuration.getSqlFragments());
					xmlMapperBuilder.parse();
				} catch (Exception e) {
					throw new NestedIOException("Failed to parse mapping resource: '" + resources[i] + "'", e);
				} finally {
					ErrorContext.instance().reset();
				}
			}
		}
	}

}
 
Example 11
Source File: ProcessEngineConfigurationImpl.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
protected Configuration parseCustomMybatisXMLMappers(Configuration configuration) {
    if (getCustomMybatisXMLMappers() != null)
        // see XMLConfigBuilder.mapperElement()
        for (String resource : getCustomMybatisXMLMappers()) {
            XMLMapperBuilder mapperParser = new XMLMapperBuilder(getResourceAsStream(resource),
                    configuration, resource, configuration.getSqlFragments());
            mapperParser.parse();
        }
    return configuration;
}
 
Example 12
Source File: XmlMapperBuilderTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
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();
}
 
Example 13
Source File: XmlMapperBuilderTest.java    From mybatis with Apache License 2.0 5 votes vote down vote up
@Test
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();
}
 
Example 14
Source File: AbstractEngineConfiguration.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
protected void parseMybatisXmlMapping(Configuration configuration, String resource) {
    // see XMLConfigBuilder.mapperElement()
    XMLMapperBuilder mapperParser = new XMLMapperBuilder(getResourceAsStream(resource), configuration, resource, configuration.getSqlFragments());
    mapperParser.parse();
}
 
Example 15
Source File: MyBatisDataStore.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Registers a templated {@link DataAccess} type with MyBatis.
 */
@SuppressWarnings("unchecked")
private void registerTemplatedMapper(final Class<? extends DataAccess> accessType, final Class<?> templateType) {

  // make sure any types expected by the template are registered first
  Expects expects = templateType.getAnnotation(Expects.class);
  if (expects != null) {
    asList(expects.value()).forEach(expectedType -> {
      if (expectedType.isAnnotationPresent(SchemaTemplate.class)) {
        // also a template which we need to resolve using the current context
        register(expectedAccessType(accessType, templateType, expectedType));
      }
      else {
        register(expectedType);
      }
    });
  }

  // lower-case prefix of the access type, excluding the package; for example MavenAssetDAO / AssetDAO = maven
  String prefix = extractPrefix(accessType.getSimpleName(), templateType.getSimpleName());

  // the variable in the schema XML that we'll replace with the local prefix
  String placeholder = templateType.getAnnotation(SchemaTemplate.class).value();

  // load and populate the template's mapper XML
  String xml = loadMapperXml(templateType, true)
      .replace("${namespace}", accessType.getName())
      .replace("${" + placeholder + '}', prefix);

  // now append the access type's mapper XML if it has one (this is where it can define extra fields/methods)
  String includeXml = loadMapperXml(accessType, false);
  Matcher mapperBody = MAPPER_BODY.matcher(includeXml);
  if (mapperBody.find()) {
    xml = xml.replace("</mapper>", format("<!-- %s -->%s</mapper>", accessType.getName(), mapperBody.group(1)));
  }

  try {
    log.trace(xml);

    Configuration mybatisConfig = sessionFactory.getConfiguration();

    XMLMapperBuilder xmlParser = new XMLMapperBuilder(
        new ByteArrayInputStream(xml.getBytes(UTF_8)),
        mybatisConfig,
        mapperXmlPath(templateType) + "${" + placeholder + '=' + prefix + '}',
        mybatisConfig.getSqlFragments(),
        accessType.getName());

    xmlParser.parse();

    // when the type is not visible from this classloader then MyBatis will prepare the mapper
    // but not do the final registration - so this call is needed to complete the registration
    if (!mybatisConfig.hasMapper(accessType)) {
      mybatisConfig.addMapper(accessType);
    }
  }
  catch (RuntimeException e) {
    log.warn(xml, e);
    throw e;
  }
}