2013-04-09 54 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

相關問題