开发者

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

I have an Entity. And sometimes I need this object also contains some value, call it 'depth'. The query may look like 'select b.id, b.name, b..., count(c.id) as depth from Entity b, CEntity c where ...'. So I've created class NonHibernateEntity which extends Enti开发者_如何转开发ty. And then results of query written above are perfectly stored as List of NonHibEntity, which consists of all the fields of Entity (as they are extended), and property 'depth'. I make it by setting aliasToBean results transformer: .setResultTransformer(Transformers.aliasToBean(NHEntity.class)). But, it is annoying and inconvenient - to specify all the aliases of all the needed fields. And then, if I want to save one of this object to DB - session.saveOrUpdate((Enity)nHibEntity) - there are an exception about nHibEntity isn't Hibernate Entity.

I heard about storing 'entity' as field in NonHibEntity (aggregation, not inheritance). But it seems this is rather inconvenient too. What do you think? What is an appropriate solution?


A Formula column mapping may be suitable for your needs. I would try this first.

If this causes performance issues as you fear, you might try a mapped class hierarchy with this field only in the child, and mapping both to the same table. Not sure this will actually work though...

As a last resort, do what you've got now using a non-mapped class, but with the entity as a field in your other class - aggregation instead of inheritance as you say, and make sure there's a way of retrieving the mapped entity from the unmapped one so that you can save. It be sensible to make it a Decorator, so that it's both a subclass and aggregate and you can continue to ignore the distinction in much of your code.

With the non-mapped subclass and/or aggregate, however, you'll have to pull out the entity in order to save.


If somebody want to know - I solved this problem in such 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 good, and seems that it can be easily supported in future

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜