Search code examples
hibernateliferayhibernate-mapping

Liferay error org.hibernate.MappingException: Unknown entity: com.mycompany.myapp.model.MyModel


I am using Liferay 6.2 GA5 Community Edition.

I created entities normally in my service.xml, run a Service Builder, and successfully generated all classes files. I tried any CRUD operation in MyModel model and always get success result.

I have a Stored Procedure whose output list of records, a record represents MyModel. Then I try to call that Stored Procedure like this:

SessionFactory sessionFactory = (SessionFactory) PortalBeanLocatorUtil.locate("liferaySessionFactory");
Session session = null;
try {
    session = sessionFactory.openSession();
    SQLQuery query = session.createSQLQuery("{ CALL dbo.USP_GET_CHILD(:abc) }");
    query.addEntity("MyModel", MyModel.class).setString("abc", "aaa");
    List<MyModel> list = (List<MyModel>) query.list();
    _log.info("size: " + list.size());
    for (MyModel o : list) {
        _log.info("result: " + o.getFullName());
    }
} catch (Exception e) {
    _log.error(e.getMessage(), e);
}

From code above, I get error org.hibernate.MappingException: Unknown entity: com.mandiri.ipsplus.model.MyModel at line query.list()

I know it happened because I put .addEntity("MyModel", MyModel.class),

but if I didn't do that I will always get ClassCastCastException at line for (MyModel o : list) because I was trying to cast Hibernate default model into MyModel.

After searching this kind of exception, I got some article in Hibernate-specific topics, that saying I must put @Entity annotation in MyModel. But in Liferay, model will always be generated from service.xml, right?

How to solve this problem? Is there any attribute in service.xml or any XML file configuration that can solve this?

thank you very much


Solution

  • Are you mixing ServiceBuilder-generated entities with raw hibernate access? I'd rather suggest that you either stay on the ServiceBuilder side (which mostly hides hibernate from you) or you go hibernate all the way and omit ServiceBuilder.

    Within the context of Liferay (e.g. the need to cover applications deployed in several contexts) ServiceBuilder has its advantages: You can easily access your API in all plugins/portlets, no matter which web application they're deployed in.