问题
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