How can we fetch liferay entities through custom-finder using custom SQL?
Following is my sql query written in
default.xml
(I have trimmed down the query to the bare minimum so that the logic remains simple. Since it included a few functions and joins we couldn't useDynamicQuery
API ):SELECT grp.* FROM Group_ WHERE site = 1 AND active_ = 1 AND type_ <> 3
Relevant code in
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); }
This above code won't work as the GroupImpl
class is present in portal-impl.jar
and this jar cannot be used in custom portlet.
I also tried using sqlQuery.addEntity("Group_", PortalClassLoaderUtil.getClassLoader().loadClass("com.liferay.portal.model.impl.GroupImpl"))
But this above code throws exception:
com.liferay.portal.kernel.exception.SystemException:
com.liferay.portal.kernel.dao.orm.ORMException:
org.hibernate.MappingException:
Unknown entity: com.liferay.portal.model.impl.GroupImpl
But the same code works for our custom-entity, if we write sqlQuery.addEntity("MyCustomGroup", MyCustomGroupImpl.class);
.
Thanks