我们如何使用自定义 SQL 通过自定义查找器获取 Liferay 实体?
default.xml
编写的 sql 查询(我已将查询缩减到最低限度,以便逻辑保持简单。由于它包含一些函数和连接,我们无法使用 DynamicQuery
API ):SELECT
grp.*
FROM
Group_
WHERE
site = 1
AND active_ = 1
AND type_ <> 3
MyCustomGroupFinderImpl.java
:Session session = null;
try {
session = openSession();
// fetches the query string from the default.xml
String sql = CustomSQLUtil.get(FIND_ONLY_ACTIVE_SITES);
SQLQuery sqlQuery = session.createSQLQuery(sql);
sqlQuery.addEntity("Group_", GroupImpl.class);
// sqlQuery.addEntity("Group_", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.GroupImpl"));
return (List<Group>) QueryUtil.list(sqlQuery, getDialect(), 0, QueryUtil.ALL_POS);
}
catch (Exception e) {
throw new SystemException(e);
}
finally {
closeSession(session);
}
上面的代码不能用作
GroupImpl
类存在于 portal-impl.jar
并且此 jar 不能在自定义 portlet 中使用。我也尝试使用
sqlQuery.addEntity("Group_", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.GroupImpl"))
但是上面的代码抛出异常:com.liferay.portal.kernel.exception.SystemException:
com.liferay.portal.kernel.dao.orm.ORMException:
org.hibernate.MappingException:
Unknown entity: com.liferay.portal.model.impl.GroupImpl
但是相同的代码适用于我们的自定义实体,如果我们写
sqlQuery.addEntity("MyCustomGroup", MyCustomGroupImpl.class);
.谢谢
最佳答案
我是从liferay forum thread发现的而不是 session = openSession();
我们需要从 liferaySessionFactory
获取 session 如下使其工作:
// fetch liferay's session factory
SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");
Session session = null;
try {
// open session using liferay's session factory
session = sessionFactory.openSession();
// fetches the query string from the default.xml
String sql = CustomSQLUtil.get(FIND_ONLY_ACTIVE_SITES);
SQLQuery sqlQuery = session.createSQLQuery(sql);
// use portal class loader, since this is portal entity
sqlQuery.addEntity("Group_", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.GroupImpl"));
return (List<Group>) QueryUtil.list(sqlQuery, getDialect(), 0, QueryUtil.ALL_POS);
}
catch (Exception e) {
throw new SystemException(e);
}
finally {
sessionFactory.closeSession(session); // edited as per the comment on this answer
// closeSession(session);
}
希望这对 stackoverflow 上的某人有所帮助,我也发现了一个不错的 tutorial关于 custom-sql 也使用相同的方法。
关于sql - 如何通过自定义插件portlet中的custom-finder获取liferay实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15895484/