Search in sources :

Example 1 with XMLStatementBuilder

use of org.apache.ibatis.builder.xml.XMLStatementBuilder in project yyl_example by Relucent.

the class MybatisBoundSqlExample method main.

public static void main(String[] args) throws IOException {
    // 解决一个不同包引起的冲突
    System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
    Configuration configuration = new Configuration();
    MapperBuilderAssistant builderAssistant = new MapperBuilderAssistant(configuration, null);
    // 定义 NameSpace
    builderAssistant.setCurrentNamespace("sample");
    try (InputStream input = MybatisBoundSqlExample.class.getResourceAsStream("sample-mapper.xml")) {
        // XML XPath解析器
        XPathParser parser = new XPathParser(input);
        // 获得select节点
        for (XNode node : parser.evalNodes("/mapper/select")) {
            // 解析节点
            XMLStatementBuilder statementParser = new XMLStatementBuilder(configuration, builderAssistant, node, null);
            // 这个操作会创建 MappedStatement ,并保存到configuration中
            statementParser.parseStatementNode();
        }
    }
    // 获得 getById
    MappedStatement ms = configuration.getMappedStatement("sample.selectList");
    // 定义参数
    Map<String, String> parameters = new HashMap<>();
    parameters.put("id", "1");
    // 根据参数获得 BoundSql
    BoundSql boundSql = ms.getBoundSql(parameters);
    // 打印最终SQL 和 参数
    System.out.println("[SQL]");
    System.out.println(boundSql.getSql());
    System.out.println("[PARAMETER]");
    for (ParameterMapping pm : boundSql.getParameterMappings()) {
        System.out.println(pm.getProperty() + "=>" + parameters.get(pm.getProperty()));
    }
}
Also used : XPathParser(org.apache.ibatis.parsing.XPathParser) Configuration(org.apache.ibatis.session.Configuration) ParameterMapping(org.apache.ibatis.mapping.ParameterMapping) HashMap(java.util.HashMap) BoundSql(org.apache.ibatis.mapping.BoundSql) InputStream(java.io.InputStream) XNode(org.apache.ibatis.parsing.XNode) MappedStatement(org.apache.ibatis.mapping.MappedStatement) MapperBuilderAssistant(org.apache.ibatis.builder.MapperBuilderAssistant) XMLStatementBuilder(org.apache.ibatis.builder.xml.XMLStatementBuilder)

Aggregations

InputStream (java.io.InputStream)1 HashMap (java.util.HashMap)1 MapperBuilderAssistant (org.apache.ibatis.builder.MapperBuilderAssistant)1 XMLStatementBuilder (org.apache.ibatis.builder.xml.XMLStatementBuilder)1 BoundSql (org.apache.ibatis.mapping.BoundSql)1 MappedStatement (org.apache.ibatis.mapping.MappedStatement)1 ParameterMapping (org.apache.ibatis.mapping.ParameterMapping)1 XNode (org.apache.ibatis.parsing.XNode)1 XPathParser (org.apache.ibatis.parsing.XPathParser)1 Configuration (org.apache.ibatis.session.Configuration)1