1.SQL的格式
SQL是放在xml中的,一個典型的SQL配置文件如下:
<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");
// 把<![CDATA[中的值賦給方法的第二個參數
digester.addCallParam("sqlList/sql", 1);
// 解析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能否被正確讀入。