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 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" +
" select count(*) from users u where u.id inn" +
" n" +
" ${item} n" +
" n" +
" n" +
" ";
Configuration configuration = new Configuration();
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(new ByteArrayInputStream(sql.getBytes()),
configuration, "", configuration.getSqlFragments());
xmlMapperBuilder.parse();
Map 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 xNodes = xNode.evalNodes("select|insert|update|delete");
LanguageDriver languageDriver = new XMLLanguageDriver();
SqlSource sqlSource = languageDriver.createSqlSource(configuration, xNodes.get(0), Object.class);
Map map = Maps.newHashMap();
map.put("ids", Lists.newArrayList(1, 2, 3, 4, 5));
BoundSql boundSql = sqlSource.getBoundSql(map);
System.out.println(boundSql.getSql());
}
}



