0

Is it possible to persist an artificial property in Grails 2.5.x GORM?

Using Hibernate 4 annotations / settings would also be possible.

e.g., I'd like to be able to persist DomainObjectC to a domain_object_c table with 3 columns (id, do_b_id, do_a_id) to denormalize do_a_id.

How can I make GORM create & populate the domain_object_c.do_a_id column?:

class DomainObjectA {}

class DomainObjectB {
    DomainObjectA doA
}

class DomainObjectC {
    DomainObjectB doB
    Long getDoAId() {doB?.doAId}
}
XDR
  • 4,070
  • 3
  • 30
  • 54
  • I don't understand what you are asking. If you want something persisted, why not have that field within the class? – tylerwal Dec 12 '15 at 02:09
  • Because, `DomainObjectC#doAId` should always be the same as `DomainObjectC#doB?.doAId`. My code structure enforces that in a simple manner, and doesn't use any extra memory. – XDR Dec 12 '15 at 04:16
  • What would be the purpose of copying `DomainObjectB.doA` into `DomainObjectC`? It can be done, but how do you intend to keep the copy in sync? – Emmanuel Rosa Dec 12 '15 at 14:32
  • The purpose is database denormalization, to speed up queries. You keep the copy in sync by only updating the database via GORM. This doesn't copy `DomainObjectB.doA` into `DomainObjectC`. It just has a wrapper method to access the `id` of `doA`. The purpose of the wrapper is to provide an easy way for GORM to persist the correct denormalized data to the `domain_object_c` table. I just don't know the correct GORM or Hibernate config / annotation to make that read-only property persist/ – XDR Dec 13 '15 at 06:33

1 Answers1

0

Here is what you can do:

class DomainObjectB {
    DomainObjectA doA

    //To keep in sync the data of DoaminObjectC table
    def beforeUpdate(){
        if (this.isDirty('doA')){
            DomainObjectC.findAllByDoB(this)*.setDob(this).save()
        }
    }
}

class DomainObjectC {
    DomainObjectB doB
    Long doAId

    public void setDoB(DomainObjectB doB){
        this.doB = doB
        doAId = doB?.doAId
    }
}
Sandeep Poonia
  • 2,158
  • 3
  • 16
  • 29