Grails syntax for joining tables on composite foreign key
Could anyone please tell me how to join tables in Grails? I need help with the syntax.
Let's say I have three tables and they don't have any explicitly defined foreign key constraints:
EMPLOYEE:
empid
name
emp_deptid
emp_teamid
title
salary
hiredate
DEPT:
dept_deptid
deptname
location
size
numOfTeams
TEAM:
team_teamid
teamname
team_deptid
responsibility
size
I want to join EMPLOYEE and TEAM on TEAMID and DEPTID. I know how to join tables in a SQL query. I would actually like to know how to do the table joins in Grails(on these selected columns using OnetoOne, OnetoMany, hasMapped, etc.). thanks
edit:
Class Emp(){
String empid
String teamid
String deptid
.....
.....
Date hiredate
Team team
static mapping = {
....
....
deptid column:'emp_deptid'
teamid column:'emp_teamid'
.....
.....
team column: ['teamid', 'deptid']
}
}
Class Team(){
...
...
String teamid
String deptid
static mapping ={
...
deptid column:'t开发者_开发问答eam_deptid'
teamid column:'team_teamid'
....
}
}
There are 2 subsections in GORM doc section 5.4.1 and 5.4.2, both named "Querying Associations".
edit:
Suddenly, it's not that easy - sorry for being inattentive.
Grails officially supports syntax for only compound primary keys, not foreign. I found a bunch of issues about composite foreign keys in Grails: GRAILS-4606 and GRAILS-4256.
I can propose approaches that might work, but I didn't test this myself.
A "list of columns" syntax (sample taken from GRAILS-4256):
class Employee {
Team team
static mapping = {
// ... column mapping
team column: [team_id, dept_id]
}
}
Lauro Becker used custom configuration class that adds composite foreign key mapping syntax - this looks to have worked for him.
Some people even create updatable database views with a single key field, and map domain to them, not to original tables - but I believe that's an overkill.
There are lots of ways to query and join in grails. Here's one example of a simple way to do a SQL join of two tables:
class Dept {
...
}
class Team {
...
Dept dept
}
Team.list(fetch: [dept: 'eager'])
精彩评论