Mybatis 自动构造SQL学习

Mybatis 自动构造SQL学习
输出均为

select count(*) from users u where u.id in
         (      
            1  
         ,     
            2  
         ,     
            3  
         ,     
            4  
         ,     
            5  
         )

三种方式


import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.builder.xml.XMLMapperEntityResolver;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.parsing.XNode;
import org.apache.ibatis.parsing.XPathParser;
import org.apache.ibatis.scripting.xmltags.XMLLanguageDriver;
import org.apache.ibatis.session.Configuration;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayInputStream;
import java.util.List;
import java.util.Map;

/**
 *
 */
class LanguageDriverRegistryTest2 {

  @Test
  void registerByInstanceNull() {
    String sql = "";

    Configuration configuration = new Configuration();
    LanguageDriver languageDriver = new XMLLanguageDriver();
    SqlSource sqlSource = languageDriver.createSqlSource(configuration, sql, Object.class);
    Map<String, Object> map = Maps.newHashMap();
    map.put("ids", Lists.newArrayList(1, 2, 3, 4, 5));
    BoundSql boundSql = sqlSource.getBoundSql(map);
    System.out.println(boundSql.getSql());
  }

  @Test
  void XMLMapperBuilder() {
    String sql = "\n" +
      "\n" +
      "\n" +
      "    \n" +
      "";

    Configuration configuration = new Configuration();
    XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(new ByteArrayInputStream(sql.getBytes()),
      configuration, "", configuration.getSqlFragments());
    xmlMapperBuilder.parse();
    Map<String, Object> map = Maps.newHashMap();
    map.put("ids", Lists.newArrayList(1, 2, 3, 4, 5));
    BoundSql boundSql = configuration.getMappedStatement("query").getBoundSql(map);
    System.out.println(boundSql.getSql());


  }

  @Test
  void XMLMapperBuilder2() {
    String sql = "\n" +
      "\n" +
      "\n" +
      "    \n" +
      "";

    Configuration configuration = new Configuration();
    XPathParser parser = new XPathParser(new ByteArrayInputStream(sql.getBytes()),
      true, configuration.getVariables(), new XMLMapperEntityResolver());
    XNode xNode = parser.evalNode("/mapper");
    List<XNode> xNodes = xNode.evalNodes("select|insert|update|delete");
    LanguageDriver languageDriver = new XMLLanguageDriver();
    SqlSource sqlSource = languageDriver.createSqlSource(configuration, xNodes.get(0), Object.class);
    Map<String, Object> map = Maps.newHashMap();
    map.put("ids", Lists.newArrayList(1, 2, 3, 4, 5));
    BoundSql boundSql = sqlSource.getBoundSql(map);
    System.out.println(boundSql.getSql());
  }
}

你可能感兴趣的:(java,apache,java,服务器)