Java Code Examples for org.apache.ibatis.builder.xml.XMLMapperBuilder#parse()

The following examples show how to use org.apache.ibatis.builder.xml.XMLMapperBuilder#parse() . 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: MapperAnnotationBuilder.java    From mybaties with Apache License 2.0 6 votes vote down vote up
private void loadXmlResource() {
  // Spring may not know the real resource name so we check a flag
  // to prevent loading again a resource twice
  // this flag is set at XMLMapperBuilder#bindMapperForNamespace
  if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
    String xmlResource = type.getName().replace('.', '/') + ".xml";
    InputStream inputStream = null;
    try {
      inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
    } catch (IOException e) {
      // ignore, resource is not required
    }
    if (inputStream != null) {
      XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
      xmlParser.parse();
    }
  }
}
 
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: MapperAnnotationBuilder.java    From mybatis with Apache License 2.0 6 votes vote down vote up
private void loadXmlResource() {
  // Spring may not know the real resource name so we check a flag
  // to prevent loading again a resource twice
  // this flag is set at XMLMapperBuilder#bindMapperForNamespace
  if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
    String xmlResource = type.getName().replace('.', '/') + ".xml";
    InputStream inputStream = null;
    try {
      inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
    } catch (IOException e) {
      // ignore, resource is not required
    }
    if (inputStream != null) {
      XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
      xmlParser.parse();
    }
  }
}
 
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: SqlSessionFactory.java    From sumk with Apache License 2.0 5 votes vote down vote up
SqlSessionFactory sqlParse() throws Exception {
	Map<String, byte[]> sqls = resourceLoader.get().openResources(db);
	Set<Map.Entry<String, byte[]>> entries = sqls.entrySet();
	for (Map.Entry<String, byte[]> entry : entries) {
		byte[] bs = entry.getValue();
		XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(new ByteArrayInputStream(bs), configuration,
				entry.getKey(), configuration.getSqlFragments());
		xmlMapperBuilder.parse();
	}
	return this;
}
 
Example 11
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 12
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 13
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 14
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 15
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 16
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;
  }
}