Self-made xml implements SQL dynamic parameter configuration and self-made xmlsql dynamic

Source: Internet
Author: User

Self-made xml implements SQL dynamic parameter configuration and self-made xmlsql dynamic

This article is based on Spring MVC + Spring + Hibernate platform.

 

I. Preparations

1. Click here to find and download commons-digester3-3.2.jar

2. Click here to find and download commons-beanutils-1.9.3.jar

Current maximum version

3. Put the jar package to the lib directory of the project.

 

Ii. Related code

1. xml Parser: SqlXmlParser. java

Package com. ims. persistence. base; import java. io. file; import java. io. fileInputStream; import java. io. inputStream; import java. text. messageFormat; import java. util. arrayList; import java. util. list; import java. util. map; import org. apache. commons. digester3.Digester; import org. apache. commons. lang3.StringUtils; import org. apache. log4j. logger; public class SqlXmlParser {private String sqlXml; private static Dig Ester digester; private static String webrootPath = System. getProperty ("webapp. root ") +" SQL/"; private static Logger logger = Logger. getLogger (SqlXmlParser. class); static {digester = new Digester (); digester. setValidating (false); digester. addObjectCreate ("set", SqlSet. class); digester. addObjectCreate ("set/SQL", SQL. class); digester. addSetProperties ("set/SQL"); digester. addBeanPropertySetter ("set/sq L/pattern "); digester. addSetNext ("set/SQL", "addSql"); digester. addObjectCreate ("set/SQL/param", SqlParam. class); digester. addSetProperties ("set/SQL/param"); digester. addSetNext ("set/SQL/param", "addParam");} public SqlXmlParser (String sqlXml) {this. sqlXml = sqlXml;} public String parse (String sqlName, Map <String, String> params) {InputStream is = null; String result = null; try {is = new FileIn PutStream (new File (webrootPath + sqlXml); SqlSet sqlSet = (SqlSet) digester. parse (is); SQL SQL = sqlSet. getSqls (). get (sqlName); List <String> paramList = new ArrayList <String> (); for (SqlParam param: SQL. getCondition () {String value = params. get (param. getName (); paramList. add (param. getPosition (), StringUtils. isBlank (value )? "": Value);} result = MessageFormat. format (SQL. getPattern (), paramList. toArray ();} catch (Exception e1) {logger. error ("SQL File Parsing exception:" + e1);} finally {if (is! = Null) {try {is. close ();} catch (Exception e2) {logger. error ("SQL file stream close exception:" + e2) ;}is = null; digester. clear () ;}} return result ;}}
View Code

  

2. SqlSet. java

package com.ims.persistence.base;import java.util.HashMap;import java.util.Map;public class SqlSet {    private Map<String, Sql> sqls = new HashMap<String, Sql>();    public void addSql(Sql sql){        sqls.put(sql.getName(), sql);    }        public Map<String, Sql> getSqls() {        return sqls;    }    public void setSqls(Map<String, Sql> sqls) {        this.sqls = sqls;    }}
View Code

  

3. SQL. java

package com.ims.persistence.base;import java.util.ArrayList;import java.util.List;public class Sql{    private String name;    private String pattern;    private List<SqlParam> condition = new ArrayList<SqlParam>();        public void addParam(SqlParam param){        condition.add(param);    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPattern() {        return pattern;    }    public void setPattern(String pattern) {        this.pattern = pattern;    }    public List<SqlParam> getCondition() {        return condition;    }    public void setCondition(List<SqlParam> condition) {        this.condition = condition;    }}
View Code

  

4. SqlParam. java

package com.ims.persistence.base;public class SqlParam {    private String name;    private Integer position;        public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }        public Integer getPosition() {        return position;    }    public void setPosition(Integer position) {        this.position = position;    }}
View Code

  

5. Put the xml file containing SQL statements in the WebContent/SQL directory, for example:

<?xml version="1.0" encoding="utf-8" ?><set>    <sql name="codeType">        <pattern>            <![CDATA[                select A.id, A.value, A.text                 from sys.code A                 left join sys.codeType B on A.codeTypeId = B.id                 where (case when "{0}"="" then 1=1 else B.codeType = "{0}" end)                    and (case when "{1}"="" then 1=1 else A.isEnable = "{1}" end)                    and (case when "{2}"="" then 1=1 else A.isDefault = "{2}" end)            ]]>        </pattern>            <param name="codeType" position="0" />        <param name="isEnable" position="1" />        <param name="isDefault" position="2" />            </sql></set>
View Code

  

6. Use methods such:

package com.ims.service.xxx.impl;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import com.ims.persistence.base.SqlXmlParser;import com.ims.persistence.dao.xxx.CodeDao;import com.ims.service.xxx.CodeBS;@Service("codeBS")public class CodeBSImpl implements CodeBS{    private static final String sqlXml = "xxx/code.xml";    @Autowired    private CodeDao codeDao;        @Override    public List<Map<String, Object>> getValueTextListByType(String codeType) {        Map<String, String> paramMap = new HashMap<String, String>();        paramMap.put("codeType", codeType);        List<Map<String, Object>> list = codeDao.findBySql(new SqlXmlParser(sqlXml).parse("codeType", paramMap));        List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();        for(Map<String, Object> map:list){            Map<String, Object> temp = new HashMap<String, Object>();            temp.put("value", map.get("value"));            temp.put("text", map.get("text"));            result.add(temp);        }        return result;    }}
View Code

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.