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

隐身守侯 提交于 2019-12-10 15:29:59

问题


I'm working with 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


回答1:


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()


来源:https://stackoverflow.com/questions/5911990/gorm-list-all-the-domain-instances-belonging-to-user-root-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!