开发者

Grails syntax for joining tables on composite foreign key

开发者 https://www.devze.com 2023-04-04 22:36 出处:网络
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:

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'])
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号