开发者

GORM: List all the domain instances belonging to User (root object)

I'm working 开发者_如何学Cwith grails since a while. There is something I still don't know how to implement correctly.

I have a domain class (let's say User) which contains a List which can be potentially any domain class (Item, User, etc, etc). Is there a way to make this out of the box?

At the moment I'm doing it the following way:

I have a UserLink which contains following properties:

class UserLink{
    User user
    String className
    Long refId
}

Then I have a service which loads all links for a given user and then the corresponding objects in the link, and returns them as a list.

I think this approach is not the best, and could lead to future performance problems

What do you think? Do you have better design ideas?

Thanks, Nicolas


Is it really any, or only a certain subset of classes? I believe you'll have some more domain classes not directly related to User.

If so, you can create a UserAsset class or interface with a belongsTo=[user: User] prop, and inherit/implement it.

Then find all domain classes implementing it, and query each with clazz.findByUser(), like:

GrailsClass[] classes = grailsApplication.getArtefacts('Domain')
GrailsClass[] userAssetClasses = 
    classes.clazz.findAll { UserAsset.class.isAssignableFrom(it) }
List<UserAsset> allUserAssets = 
    userAssetClasses.clazz*.findAllByUser(myUser).flatten()

edit: If we're talking M:M, it only changes last line, the way userAssetClasses are queried.

UserAsset will have a hasMany=[users:User] property.

Like:

List<UserAsset> allUserAssets = userAssetClasses.clazz.collect{ 
    Class domainClass ->
    it.withCriteria {
        users {
            eq('id', myUser.id)
        }
    }
}.flatten()
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜