开发者

create dynamic query Ibatis

Is there any way to pass dynamic column names ?

we can pass values ussing ##

value#

Where #columnName# = #value#

not 开发者_StackOverflowwork for me


This is my solution by generate dynamic queryes from IBatis:.

The configuration Object for the query:

[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; }
        }
    }

The 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>


You can build a string for the entire WHERE clause, put it in your parameter object, and then reference it in your iBATIS XML like this:

select *
from blah
where ?whereClause?

The '?' on the ends of a parameter tells iBATIS to use its contents as-is. This can open the door to potential risks (SQL injection, etc.), so be sure to check your parameters thoroughly before proceeding with this method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜