MyBatis – 如何创建w动态WHERE子句

该服务获取一个包含三个值列表的未知对象[column,operator,value]例如,EMAIL – like – “TEST”

基于结果列表来构建我有的WHERE子句但我也能够构建如下的条件(例如)

WHERE(电子邮件,如’test’和user_id 5)或(trans_id 500)

有谁可以帮我怎么做?

我自己长期缺席后一直在重新发现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 params1 = new ArrayList(); params1.add(new Clause("email","like","test")); params1.add(new Clause("user","<>",5)); ArrayList params2 = new ArrayList(); 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环境之外工作。

      

这个答案有两个关键部分。 一个是“动态”元素,另一个是你问题中“运算符”周围的$$文字元素。

   

另请参阅有关此主题的DataMapper Dynamic SQL文档 。