I need to run a query on 2 legacy tables but both the join columns are not the primary key, by example is clearer:
The 2 one-to-one domain classes:
class DocumentStatus {
String id
String messageID
static hasOne = [activity: Activity]
static constraints = {
activity unique: true
}
static mapping = {
datasource 'messages'
table 'DocumentStatus'
cache usage: 'read-only'
version false
id column: 'UniqueID', generator: 'assigned'
messageID column: 'MessageID', insertable: false, updateable: false
activity column: 'MessageID', ignoreNotFound: true, cache: true, /*lazy: false, */fetch: 'join'
}
}
and
class Activity {
String id
String messageId
DocumentStatus documentStatus
static belongsTo = [DocumentStatus]
static mapping = {
datasource 'messages'
version false
cache usage: 'read-only'
table 'Activity'
id column: 'aid', generator: 'assigned'
messageId column: 'messageid', insertable: false, updateable: false
documentStatus column: 'messageid', cache: true
}
static constraints = {
documentStatus unique: true
}
}
The SQL run is (only essential part shown here):
"inner join activity activity_a1_ on this_.uniqueid=activity_a1_.messageid "
but what I need is to change the join column on DocumentStatus aka “this_” to be “messageId”.
The where clause basically is:
def query = DocumentStatus.where {
dateTime >= dateFrom && dateTime <= dateTo &&
status in docStatusList
}
if (buyerId) {
query = query.where {
activity.senderId == buyerId
}
}
def results = query.list(sort: "dateTime", max: 100)
I’ve tried various combinations but can’t get the comparison to be messageId on both sides of the join.
This was resolved by adding a new domain class mapped to a table that has messageId as its PK, this then acts as the master which the other classes hang from:
}
I’m still not sure why the original issue was there (perhaps this user is in error 🙂 ), surely I can join DomainA.FK = DomainB.FK. In the end this approach for my case actually was a better solution anyway by starting with the class with the PK and branching out on DomainA.PK = DomainB.FK
Hope that helps someone