开发者

Projection in Grails

Could you please tell me how to do a projection on a Grails domain class?! In my case, I want to get a list of (for example) User's name by their Ids. It means in my method, I pass a list of userId and get a list of user's names. Does dynamic methods of Groovy domain support this feature? At present, I'm using my below function:

public String getUserNamesByIds(String[] ids) {
    StringBuffer names = User.get(Integer.parseInt(ids[0]).getName())
    if(ids.length > 1) {
        (1..ids.length - 1).each{
             names.append(", " + User.get(Integer.parseInt(ids开发者_Python百科[it])).getName())
        }
    }
    return names.toString()
}

As you see, I just want to get the name (and build the total string). I think it's not good because I have to do many small steps, and perform many queries to database to get the User object. Is there any better method to do this? Thank you so much!


You can use a Criteria and with projections to get the names of the users given its IDs, doing something like:

public List getUserNamesByIds(String[] ids) {
    def criteria = User.createCriteria()
    return criteria.list {
       projections {
         property("name")
       }
       'in'("id", ids)
    }
}

Then you can convert the List of user names into the a String by doing:

List users = getUserNamesByIds(...)
String concatenatedNames = (users ? users.join(",") : "")

You can read more about criterias and projections here in the Grails user guide.


That's a terrible idea. The reason is every call to User.get(id) makes a call over the wire across the network. This is very expensive, and even if your database responds in 20 ms doing 1000 of them is going to take 20 seconds--quite a long time for your user to wait. A better idea is to get the set of users you are interested in by some sort of query then iterate over them while they are in memory. Which takes 1 ns or less for each loop invocation.

This implementation is literally one of the largest reasons web apps are slow...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜