How to add property counted in DB to class @Entity?

I have an entity. And sometimes I need this object, which also contains some value, call it "depth". The request may look like 'select b.id, b.name, b..., count(c.id) as depth from Entity b, CEntity c where ...'. So I created a NonHibernateEntity class that extends Entity. And then the query results written above are perfectly saved as a List of NonHibEntity, which consists of all Entity fields (as they expand) and the "depth" property. I do this by installing the aliasToBean result transformer: .setResultTransformer(Transformers.aliasToBean(NHEntity.class)). But, it is annoying and inconvenient to specify all the aliases of all the required fields. And then, if I want to save one of this object in DB - session.saveOrUpdate((Enity)nHibEntity)- there is an exception from nHibEntity, it is not Hibernate Entity.

I heard about saving "entity" as a field in NonHibEntity (aggregation, not inheritance). But it seems that this is also inconvenient. What do you think? What is the right solution?

+3
source share
2 answers

If someone wants to know, I solved this problem this way:

just made this calculated field as @Transient and then

List<BaseEntry> result = new ArrayList<BaseEntry>();
    Iterator it =  session()
    .createQuery("select b, (select count(p.id) as depth from BaseEntry p " +
            "   where ... ) as d" +
            " from BaseEntry b " +
            " where ... ")
    .list().iterator();
    while ( it.hasNext() ) {
        Object[] row = (Object[]) it.next();
        BaseEntry entry = (BaseEntry) row[0];
        Long d = (Long) row[1];
        entry.setD(d);
        result.add(entry);
    }
    return result;

It works well and seems easy to maintain in the future.

0
source

Source: https://habr.com/ru/post/1791536/


All Articles