我自己也时隔许久重新发现了MyBatis(我曾经也熟悉过iBatis)。 Rolf 的示例看起来可能是 .Net 实现,我可能是错的,但我不认为 Java 表示法现在看起来像那样。 Rolf 关于文字字符串的提示非常有用。
我创建了一个小类来保存列、运算符和值,并将它们传递到 MyBatis 中进行处理。列和运算符是字符串文字,但我将这些值保留为 sql 参数(我想 MyBatis 能够进行任何必要的类型转换)。
public class TestAnswer {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
SqlSessionFactory sqlFactory = (SqlSessionFactory) ctx.getBean("sqlSessionFactory");
MappedStatement statement = sqlFactory.getConfiguration().getMappedStatement("testAnswer");
ArrayList<Clause> params1 = new ArrayList<Clause>();
params1.add(new Clause("email","like","test"));
params1.add(new Clause("user","<>",5));
ArrayList<Clause> params2 = new ArrayList<Clause>();
params2.add(new Clause("trans_id","<",100));
params2.add(new Clause("session_id",">",500));
HashMap params = new HashMap();
params.put("params1", params1);
params.put("params2", params2);
BoundSql boundSql = statement.getBoundSql(params);
System.out.println(boundSql.getSql());
}
static class Clause{
private String column;
private String operator;
private Object value;
public Clause(String column, String operator, Object value){
this.column = column;
this.operator = operator;
this.value = value;
}
public void setColumn(String column) {this.column = column;}
public void setOperator(String operator) {this.operator = operator;}
public void setValue(Object value) {this.value = value;}
public String getColumn() {return column;}
public String getOperator() {return operator;}
public Object getValue() {return value;}
}
}
正如您所看到的,我使用 Spring,但我预计类似的东西可能会在 Spring 环境之外工作。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.stackoverflow.TestMapper">
<select id="testAnswer" parameterType="map" resultType="hashmap">
select *
FROM somewhere
<where>
<foreach item="clause" collection="params1" separator=" AND " open="(" close=")">
${clause.column} ${clause.operator} #{clause.value}
</foreach>
OR
<foreach item="clause" collection="params2" separator=" AND " open="(" close=")">
${clause.column} ${clause.operator} #{clause.value}
</foreach>
</where>
</select>
</mapper>