Reputation: 1585
Say I have a Domain Object User
which contains an Organization
field. I can map that using a foreign key and let hibernate take care of the rest like so:
class User {
String id
String firstName
Organization organization
static mapping = {
table 'user'
id column: "user_id", generator:'assigned'
organization column: 'organization_Id'
}
}
class Organization {
String id
String name
String address
static mapping = {
table 'organization'
id column: "organization_id", generator:'assigned'
}
}
This works fine, but when I want to query for all users in an organization I might have to do something like this
String orgId = "some id"
Organization org = Organization.findById(orgId)
List<User> users = User.findAllByOrganization(org)
It would be convenient to not have to pass the Organization
domain object and instead just pass the Organization.Id which is the foreign key on the User
table.
How I want my code to look is the following:
String orgId = "some id"
List<User> users = User.findAllByOrganization(orgId)
After researching, it seems like this is not possible, I need to first query for the Organization
and then use that object. Is there a way I am unaware of?
Upvotes: 2
Views: 772
Reputation: 20707
You have two options there:
orgId
field to you User
class and use it for the
lookup..
Organization org = new Organization()
org.id = 'someId' // looks strange, but you can not use id inside constructor
def users = Users.findAllByOrganization org
Upvotes: 1
Reputation: 19702
One way I like to do it is to use a proxy of your domain object instead of a hydrated instance of it. You can use load()
to obtain the proxy. This means no database call is made as long as you don't access any of the domain object's properties beyond the id
.
def users = Users.findByOrganization(Organization.load(orgId))
Upvotes: 5