创建动态查询Ibatis

时间:2011-10-06 12:28:20

标签: java-ee ibatis ibatis.net

有没有办法传递动态列名?

我们可以传递值##

值#

其中#columnName#= #value#

不适合我

2 个答案:

答案 0 :(得分:1)

这是我的解决方案,从IBatis生成动态查询:。

查询的配置对象:

[Serializable]
    public partial class QueryHelper
    {
        private string _queryFields;
        public string query_fields
        {
            get { return _queryFields; }
            set { _queryFields = value; }
        }

        private string _queryFrom;
        public string query_from
        {
            get { return _queryFrom; }
            set { _queryFrom = value; }
        }

        private string _queryFilterDefa;
        public string query_filter_defa
        {
            get { return _queryFilterDefa; }
            set { _queryFilterDefa = value; }
        }

        private string _queryFilterId;
        public string query_filter_id
        {
            get { return _queryFilterId; }
            set { _queryFilterId = value; }
        }

        private string _queryJoins;
        public string query_joins
        {
            get { return _queryJoins; }
            set { _queryJoins = value; }
        }

        private string _queryFilter;
        public string query_filter
        {
            get { return _queryFilter; }
            set { _queryFilter = value; }
        }

        private string _queryOrder;
        public string query_order
        {
            get { return _queryOrder; }
            set { _queryOrder = value; }
        }
    }

XML

<?xml version="1.0" encoding="utf-8" ?>
<sqlMap namespace="QueryHelper"
    xmlns="http://ibatis.apache.org/mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <alias>
    <typeAlias alias="QueryHelper" type="Core.CustomEntities.QueryHelper" />
  </alias>
  <statements>
    <select id="ExecuteQuery" parameterClass="QueryHelper" resultClass="HashTable">
      SELECT $query_fields$
      FROM $query_from$
      <isNotEmpty property="query_joins" >
        $query_joins$
      </isNotEmpty>
      WHERE $query_filter_defa$
      <isNotEmpty prepend="AND" property="query_filter_id" >
        $query_filter_id$
      </isNotEmpty>
      <isNotEmpty prepend="AND" property="query_filter" >
        $query_filter$
      </isNotEmpty>
      <isNotEmpty prepend="ORDER BY" property="query_order" >
        $query_order$
      </isNotEmpty>
    </select>
  </statements>
</sqlMap>

答案 1 :(得分:0)

您可以为整个WHERE子句构建一个字符串,将其放在您的参数对象中,然后在您的iBATIS XML中引用它,如下所示:

select *
from blah
where ?whereClause?

'?'在参数的末尾告诉iBATIS按原样使用其内容。这可以打开潜在风险的门(SQL注入等),因此在继续使用此方法之前,请务必彻底检查参数。