2013-04-09 53 views
7

我们如何使用自定义SQL通过自定义查找器获取liferay实体?如何通过自定义插件portlet中的自定义查找器获取liferay实体?

  1. 以下是我写在default.xml使逻辑仍然很简单我已经下调查询到最低限度。因为它包含的一些功能的SQL查询,并加入我们不能使用DynamicQuery API ):

    SELECT 
        grp.* 
    FROM 
        Group_ 
    WHERE 
        site = 1 
        AND active_ = 1 
        AND type_ <> 3 
    
  2. 相关的代码在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);

感谢

回答

8

我从liferay forum thread,与其session = openSession(); 我们需要从liferaySessionFactory获取会话如下,使其工作发现:

// 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); 
} 

希望这有助于#2人,我还发现一个不错的tutorial关于custom-sql也使用了相同的方法。

+0

那closeSession会调用finally块关闭那个session吗?我查看了liferay的代码,发现它使用finder的sessionFactory来关闭会话,因此我的问题。 – 2014-07-25 21:38:14

+0

@ user1316487在这种情况下,我认为它应该是'sessionFactory.closeSession(session)'。感谢您指出了这一点。 – 2014-07-28 07:58:15

相关问题