I need to track a M:N relationship with attributes, so I'm using a link table (following the pattern at Many-to-Many Mapping without Hibernate XML) ... but, I can't see how to query that Membership relationship for legal-but-don't-yet-exist relationships, e.g., any Employees not in a given Team (or Items which a User hasn't yet bid on, etc). I'm working on it in HQL, but I'm a noob to that so I could use som开发者_运维百科e guidance on what technique works best ... or, examples of this sort of query ;)
For discussion, just assume the Employees:Team Membership class, with a very large set of each (too large to just pull into the mid-tier and do set operations).
class Membership {
Employee employee
Team team
String other // I need attributes on the relationship
}
class Employee {
Date dateJoinedCompany
String name
static hasMany = [managedTeams:Team, memberships:Membership]
static mappedBy = [managedTeams:"manager"]
}
class Team {
String name
Employee manager
static belongsTo = Employee
static hasMany = [memberships:Membership]
}
So, I need a query which returns Employees not on Team #2 who jined the company more than a month ago, or Teams which Employee #5 is not part of, that sort of thing What's the best technique - is there a way to do this with Criteria? Or, any suggestions on how to best use HQL for it?
I should add my current thought, using HQL and a subselect:
from Team t where t not in (select m.team from Membership m where m.employee = 5)
TIA!
Employees not on Team #2 who jined the company more than a month ago:
Employee.executeQuery("select e from Employee as e inner join e.memberships as m where m.team.id != :tId and e.dateJoinedCompany > :date", [tId: 2, date: new Date() - 60]
//calculate the exact date. instead of using the team id you can use the team instance
Teams which Employee #5 is not part of
Team.exccuteQuery("select t from Team as t inner join t.memberships as m where m.e.id != :eId",[eId: 5])
精彩评论