ID lookup field in GORM in grails - grails

I am new to Grails and GORM and I am trying to One to Many relationship but not with default id field. Here is my scenario:
Table structure in the database:
USERPROFILE
iduserprofile
username
ROLE
idrole
rolename
USER_ROLE
iduserprofile
idrole
Domains:
class Userprofile {
long iduserprofile
String username
static mapping = {
datasource 'ALL'
id name: 'iduserprofile'
version false
}
class Role {
long idrole;
String rolename;
static mapping = {
datasource 'ALL'
id name: 'idrole'
version false
}
}
class UserRole {
Userprofile user
Role role
static mapping = {
datasource 'ALL'
version false
}
}
When I try to get the user or role object from UserRole domain, it is always looking for user_id or role_id in the USER_ROLE table.
Why is it not looking for iduserprofile or idrole? How can i change the code to look for isuserprofile or idrole?
Thanks

GORM by convention will use/generate id as identifier for your domains. If you have legacy tables or just a desire to break convention, you'll need to specify your custom column names. For example for Role mapping, add the following:
static mapping = {
datasource 'ALL'
id name: 'idrole', column: 'idrole'
version false
}

It seems to me that the easiest thing to do would be to copy your database and then change the names of the id fields if you have legacy tables. If not then just make life simple by conforming to convention.

Related

GORM using foreign key instead of domain object

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?
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))
You can use a Criteria:
String orgId = "some id"
List<User> users = User.createCriteria().list {
organization {
idEq(orgId)
}
}
You have two options there:
add a redundant orgId field to you User class and use it for the
lookup.
Use a fake object for your lookup:
.
Organization org = new Organization()
org.id = 'someId' // looks strange, but you can not use id inside constructor
def users = Users.findAllByOrganization org

GORM Mapping View

I have an Domain Class called Contact with multiple hasMany Relationships and another Domain Class Employee which is part of Concat.
Contact has an table contact and Employee should be mapped on a View which looks like this:
SELECT * FROM contact where employee=1
Employee should have the same columns and Relationship than Contact, how do I write the Domain Classes?
Can I use inheritance?
EDIT
Now I have used inheritance like this:
class Employee extends Contact { }
class Contact{
static mapping = {
tablePerHierarchy(false)
}
}
That works so far, but now I want to add some Relationships to Employee, like this:
class Employee extends Contact {
static belongsTo = [CostCenter ]
static hasMany = [costCenter: CostCenter]
static mapping = {
costCenter joinTable: 'employee_cost_center', column: 'employee_id'
}
}
class CostCenter {
static hasMany = [employees:Employee]
static mapping = {
employeesjoinTable: 'employee_cost_center', column: 'cost_center_id'
}
}
now I have the problem that the table 'employee_cost_center' makes an referen to Contact which is good, but also added 'employee_id':
contact_id
employee_id
cost_center_id
So i could add the relationships to Contact but then I have in CostCenter Contact and not Employee.
How can I add Relationships to Employee?
I think you're on track using inheritance. Since Employee is backed by a database view which selects a subset of Contacts, an Employee is a Contact. So you've got a good candidate for inheritance.
Table-per-subclass inheritance
You described the employee view as follows:
SELECT * FROM contact where employee=1
When using table-per-subclass inheritance the table generated for subclasses contain the following columns:
ID (primary key)
Columns for properties added to the subclass (are not in the superclass), excluding properties for associations.
Since Employee does not, and cannot add, additional properties, the view should only return the primary key.
SELECT id FROM contact where employee=1
I have an article that compares table-per-hierarchy to table-per-subclass inheritance and demonstrates what it looks like at the database level.
Join tables
In your domain class examples you described a join table to create the many-to-many relationship between Employee and CostCenter. Join tables should have two, and only two, columns:
The foreign key (the me domain class)
The foreign key of the other domain class.
So your employee_cost_center table should have the columns employee_id and cost_center_id. If you must specify the join table explicitly, use key instead of column.
costCenter joinTable: 'employee_cost_center', key: 'employee_id'
employees joinTable: 'employee_cost_center', key: 'cost_center_id'
belongsTo
You have Employee belong to CostCenter as so:
static belongsTo = [CostCenter ]
Maybe that's a typo, but if you're not defining a back-reference then the belongsTo should be defined as simply the class, like this:
static belongsTo = CostCenter
I've never used belongsTo this way so I don't know what it looks like in the database. But note that if you have a back-reference, defined like this:
static belongsTo = [costCenter: CostCenter]
Then, your employee view must return a cost_center column.

How can I get grails to persist a list of objects in a class?

I have the following:
GroupMember.groovy
public class GroupMember{
String userName
String role
}
GroupProfile.groovy
public class GroupProfile{
List<GroupMember> groupMembers = new ArrayList<GroupMember>()
}
GroupProfileController.groovy
public class GroupProfileController{
def createProfile{
GroupMember groupOwner = new GroupMember()
groupOwner.userName = "testUser"
groupOwner.role = "OWNER"
groupOwner.save()
GroupProfile groupProfile = new GroupProfile()
def members = grouProfile.groupMembers
members.add(groupOwner)
groupProfile.save()
GroupProfile.list() //This list contains my GroupMember instance with the correct info
redirecT(action: myProfiles)
}
def myProfiles={
GroupProfile.list() //This list contains my groupProfile that I made but no GroupMember info
}
}
My GroupProfile won't save my GroupMember info. How can I get my GroupProfile to save the GroupMember info?
The normal way to represent this relationship in grails would be:
public class GroupProfile {
static hasMany = [groupMembers: GroupMember]
}
This will automatically generate a method on GroupProfile called addToGroupMembers that will create the associations. Saving the GroupProfile will also cascade to the group members, so you'll only need to call save once after adding the members.
Note that the groupMembers collection will actually be an instance of Set that doesn't necessarily preserve order. You can explicitly declare the collection as a List to preserve order, but it requires additional overhead including an extra database column, so make sure that's really what you want.
Check out the grails manual in the section on GORM: http://grails.org/doc/latest/guide/GORM.html

Return unique results when using findAllBy

I have the following method in a service, please note the .user on the def usersByRole line:
def getUsersByRole(String desiredRole1, String desiredRole2, String desiredRole3) {
Role role1 = Role.findByAuthority(desiredRole1)
Role role2 = Role.findByAuthority(desiredRole2)
Role role3 = Role.findByAuthority(desiredRole3)
def usersByRole = UserRole.findAllByRoleInList([role1, role2, role3]).user
return usersByRole
}
It works good, but when a user has multiple roles (i.e. ROLE_ADMIN, and ROLE_OWNER) then that user exists twice in the collection if both of the previously mentioned roles are given as parameters. Is there any clean way I can make the collection contain only unique results?
A similar question as yours can be found here: GORM createCriteria and list do not return the same results : what can I do?
Method 1
If you want to return unique list of users directly from DB query then you can use listDistinct on User (supposing that user has a roles OneToMany association with UserRoles)
User.createCriteria().listDistinct {
roles {
in 'role', [role1, role2, role3]
}
}
Method 2
You can also try to query UserRole directly and group by User using the groupProperty (see http://www.grails.org/doc/latest/ref/Domain%20Classes/createCriteria.html)
Method 3
Remove duplicated users from the returned list:
UserRole.findAllByRoleInList([role1, role2, role3])*.user.unique()
The finder will return a List, and calling .user also returns a List, but you can cheat and cast it to a Set and it will remove duplicates. Since there's no order needed (you're returning def so it doesn't appear that you care about the collection type) you don't need to convert it back:
def getUsersByRole(String desiredRole1, String desiredRole2, String desiredRole3) {
Role role1 = Role.findByAuthority(desiredRole1)
Role role2 = Role.findByAuthority(desiredRole2)
Role role3 = Role.findByAuthority(desiredRole3)
return UserRole.findAllByRoleInList([role1, role2, role3]).user as Set
}
This presumes that you have a well-defined equals and hashCode in your User class so the uniqueness check makes sense.

Using hasMany in grails and postgresql

I have a postgresql database that has this column structure:
Author
id
name
Book
id
name
author_id
And Groovy Domain Classes that repressent those tables:
class Author {
static hasMany = [ books : Book ]
Integer id
String name
}
class Book {
static belongsTo = Author
Integer id
Integer project_id
String name
}
My main goal to get a list of books from a author instance.
author = Author.get( 1 ) // gets a author
author.books // must return a list of books.
But this does not work. Is there something glaringly obvious I'm doing wrong?
note I've got lots of Ruby/Rails experience and zull Java/Groovy experience.
Change your Book class to:
class Book {
static belongsTo = [authors: Author]
static mapping = {
authors column: 'author_id'
}
Integer id
Integer project_id
String name
}
If you don't specify the mapping like that, GORM will create, resp., expect, a JOIN table by default.
(BTW, domain classes are automatically provided with a "virtual" id property (of type Long I think, translating to bigint in PostgreSQL). It's not necessary to specify it manually, but it also won't harm.)
EDIT: Updated as per the questioners comments:
If a book can really have just one author, you'd state in the Book class:
Author author
static belongsTo = [author: Author]
static mapping = { author column: 'author_id' }
The GORM documentation on one-to-many relations can be found here.

Resources