【问题标题】:Grails GORM how to join legacy tables on specified keysGrails GORM如何在指定键上连接遗留表
【发布时间】:2012-02-02 05:11:57
【问题描述】:

我需要对 2 个旧表运行查询,但两个连接列都不是主键,例如更清楚:

2 个一对一的域类:

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'
   }
}

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
   }
}

SQL 运行是(此处仅显示重要部分):

"inner join activity activity_a1_ on this_.uniqueid=activity_a1_.messageid " 

但我需要将 DocumentStatus aka "this_" 上的连接列更改为 "messageId"。

where子句基本上是:

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)

我尝试了各种组合,但在连接的两边都无法比较 messageId

【问题讨论】:

    标签: hibernate grails grails-orm


    【解决方案1】:

    这是通过添加一个映射到以 messageId 作为其 PK 的表的新域类来解决的,然后它充当其他类挂起的主节点:

    class Content {
       String id
       String messageID
    
       static hasMany = [docStatus: DocumentStatus, activity: Activity]
    
       static mapping = {
        datasource 'messages' // If using multiple sources, specify
        table 'Content' // Table to map to
        cache usage: 'read-only' // If read-only
        version false  // no optimistic locking in these tables
        sort dateTime: "desc"
    
        // Map the ID column
        id column: 'MessageID', generator: 'assigned'
        // Map all other columns
    
        messageID column: 'MessageID', insertable: false, updateable: false
    
        docStatus column: 'MessageID', ignoreNotFound: true, cache: true, fetch: 'join'
        activity column: 'MessageID', ignoreNotFound: true, cache: true, fetch: 'join'
    }
    

    }

    我仍然不确定为什么会出现最初的问题(也许这个用户有误 :)),当然我可以加入 DomainA.FK = DomainB.FK。最后,对于我的情况,这种方法实际上是一个更好的解决方案,从带有 PK 的类开始并在 DomainA.PK = DomainB.FK 上扩展

    希望对某人有所帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-21
      相关资源
      最近更新 更多