简体   繁体   中英

Working Efficiently with Hibernate Spring

My code is working but my experience with spring is like 1 week old and I want to understand how things work, and how to make my code efficient as possible.

first example: I have a group object in my database and each group has posts @OneToMany

public List<Group> findAllGroups() {
    Criteria criteria = getSession().createCriteria(Group.class);
    return (List<Group>) criteria.list();
}

this return a list with 160 of the same group because I have 160 posts related to this group, So I added :

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

Is that really efficient? I mean doesn't it just gets the same list and just filters it?

How would I make it so it only does it once?

Second example:

I want to know how much posts each group has and I don't want to use group.findAllPosts().size(), What should I do about it?

It's very important for me to know this sort of stuff, Because you cant say "I can develop in Spring" while wasting so much resources.

The distinct issue is not particularly inefficient (of course depending on your situation), at least in any well behaving database. Even if it were, it's not like you have a choice. Either you filter the results out yourself or you let the database and hibernate handle it (they do it better).

For the group sizes you need (or should use) aggregate functions. In SQL it would be something like SELECT groupid, COUNT(*) FROM posts GROUP BY groupid . HQL should have something quite similar, and the criteria API has Projections for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM