服务获取一个未知对象,该对象包含三个值的列表[列,运算符,值]例如,电子邮件-如-“测试”根据生成的列表建立我的WHERE子句,但我也可以建立如下条件(例如)在哪里(电子邮件,例如'test'AND user_id 5)或(trans_id 500)有人可以帮我怎么做吗? 最佳答案 我很久没有去了(我曾经很熟悉iBatis),我一直在重新发现MyBatis。 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>关于java - MyBatis-如何创建W动态WHERE子句,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6056770/
10-12 02:44