| |
| 用Spring的Resource管理SQL的XML配置文件 |
| |
发布者: 发布时间:2008-03-12 |
|
|
在项目中,为了方便管理和修改SQL,我们一般会把SQL文放在一个专门的文件中,程序通过一个Key来访问这些SQL。Spring的资源管理做得非常好,我们的SQL资源就是用Spring进行管理的。
1.SQL的格式 SQL是放在xml中的,一个典型的SQL配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<sqlList>

<sql sqlId="SEL_FWMenuList"><![CDATA[ select t1.id,t1.name,t1.parent.id,t1.frameId from MenuInfo t1,MenuAuthority t2 where t2.menuAuthorityKey.menuInfo.id = t1.id and t2.menuAuthorityKey.role.id = :roleid order by t1.parent.id desc,t1.id
]]></sql>
</sqlList> xml的格式很简单,只有“sqlList”、“sql”、“sqlId”三个属性,每一个“sql”下面就是一条SQL。
2.利用Digester解析XML文件 Digester是Apache的解析XML的工具,使用非常方便,原理也很简单,网上介绍的资料很多,这里就不多说了,大家应该看注释就可以看懂的。在这段代码中,入口是loadSqlFile,其中is就是导入的XML文件。顺便说一下,这里在贴代码的时候,把代码中的\n\t都给弄没了,稍后我会提供实例代码,大家可以仔细看看。

 /** *//**
* load SQL Resource.<br>
*
* @param is xmlfile
* @throws IOException IOException
* @throws SAXException SAXException
* @throws SystemException SystemException
* @since 1.0.0
* <p>
*/
 private void loadSqlFile(InputStream is) throws IOException, SAXException, SystemException ...{

Digester digester = new Digester();
// 声明要调用本Class中(this)的方法
digester.push(this);

// 对XML中sqlList/sql阶层中的数据,利用addSqlInfo方法解析,该方法参数个数为2
digester.addCallMethod("sqlList/sql", "addSqlInfo", 2);

// 把sqlId中的值赋给方法的第一个参数
digester.addCallParam("sqlList/sql", 0, "sqlId");
// 把<
// 解析XML文件
digester.parse(is);
}

 /** *//**
* Add SQL Info.<br>
*
* @param sqlKey sqlKey
* @param sql sql
* @throws SystemException SystemException
* @since 1.0.0
* <p>
*/
 public void addSqlInfo(final String sqlKey, String sql) throws SystemException ...{
String sqlValue = sql;
 if (sqlKey == null) ...{
throw new SystemException();
}

// delete /*...*/
Pattern pattern = Pattern.compile("(/\*).*?(\*/)");
Matcher matcher = pattern.matcher(sqlValue);
sqlValue = matcher.replaceAll("");

// delete --
pattern = Pattern.compile("(--).*?");
matcher = pattern.matcher(sqlValue);
sqlValue = matcher.replaceAll("");

// replace
pattern = Pattern.compile("[ ]");
matcher = pattern.matcher(sqlValue);
sqlValue = matcher.replaceAll(" ");

// replace
pattern = Pattern.compile("[ ]+");
matcher = pattern.matcher(sqlValue);
sqlValue = matcher.replaceAll(" ");

sqlValue = sqlValue.trim();

this.properties.put(sqlKey, sqlValue);
} 3.Spring的配置

<bean id="sqlResource" class="sqlmanager.SQLResource"
init-method="init">
<property name="locations">
<list>
<value>classpath:framework.hql.xml</value>
<value>classpath:common.hql.xml</value>
</list>
</property>
</bean> 4.运行和测试 在实例代码SQLResource中运行main即可运行测试代码,可以测试SQL能否被正确读入。
TAG: Spring XML
|
| (转载文章请保留出处:北天JAVA技术网(www.java114.com)) |
| |
| 更多精彩文章: |
| 祝贺Guice拿了Jolt Award |
| 祝贺Guice拿了Jolt Award |
| 全球规模最大的超级计算机 |
| 全球规模最大的超级计算机 |
| 如何让JSON穿梭在服务器于浏览器之间 |
| 如何让JSON穿梭在服务器于浏览器之间 |
| |
| 最近评论: |
|
|
| 鍥炲 |
|
|
|
| |
| 免责声明:该文章由网友发表,如果对您造成侵权,请联系站长。 |
|