JcrTemplate是JCR模块的核心类之一,它提供了与JCR会话一起工作的方便方法,将调用者从必须处理的打开和关闭会话、事务回滚(如果底层仓库提供)、以及处理其它特性中的异常等工作中解放出来:
<bean id="jcrTemplate" class="org.springmodules.jcr.JcrTemplate">
<property name="sessionFactory" ref="jcrSessionFactory"/>
<property name="allowCreate" value="true"/>
</bean>
模板定义非常简单,类似来自Spring框架的其它模板类,如HibernateTemplate。
例子
既然仓库已经配置了,接下来看看“Spring化”的例子之一,它来自Jackrabbit的wiki页:
public Node importFile(final Node folderNode, final File file, final String mimeType,
final String encoding) {
return (Node) execute(new JcrCallback() {
/**
* @see org.springmodules.jcr.JcrCallback#doInJcr(javax.jcr.Session)
*/
public Object doInJcr(Session session) throws
RepositoryException, IOException {
JcrConstants jcrConstants = new JcrConstants(session);
//create the file node - see section 6.7.22.6 of the spec
Node fileNode = folderNode.addNode(file.getName(),
jcrConstants.getNT_FILE());
//create the mandatory child node - jcr:content
Node resNode = fileNode.addNode(jcrConstants.getJCR_CONTENT(),
jcrConstants.getNT_RESOURCE());
resNode.setProperty(jcrConstants.getJCR_MIMETYPE(), mimeType);
resNode.setProperty(jcrConstants.getJCR_ENCODING(), encoding);
resNode.setProperty(jcrConstants.getJCR_DATA(), new FileInputStream(file));
Calendar lastModified = Calendar.getInstance();
lastModified.setTimeInMillis (file.lastModified ());
resNode.setProperty(jcrConstants.getJCR_LASTMODIFIED(), lastModified);
session.save();
return resNode;
}
});
}
主要区别是:代码被包装在一个JCR模板中,它将我们从不得不使用的try/catch语句块(因为IO和Repository的需检查异常)和处理会话(和事务,如果有的话)清除工作中解放出来。值得提及的是硬编码字符串,如“jcr:data”,是通过JcrConstants工具类解析出来的。它知道名字空间的前缀变化,并提供一种干净的方式处理JCR常数。正如你看到的,我只是使例子更加健壮,但是对于实际业务代码影响最小。
责任编辑:小草