ilPittiz
ilPittiz

Reputation: 754

GORM - get raw DB value for domain class properties

I'm using GORM for MongoDB in my Grails 3 web-app to manage read/writes from DB.

I have the following 2 domain classes:

class Company {
  String id
}

class Team {
  String id
  Company company
}

For teams, their company is saved on DB as String, and with GORM I can simply use team.company to get an instance of Company domain class.

However, I need to override the getter for company, and I need the raw value for company id (as stored on DB), without GORM getting in the way and performing its magic. Is there a way to get the raw String value?

Any help is welcome! Thanks in advance


Update (May 27)

Investigating @TaiwaneseDavidCheng suggestion, I updated my code to

class Company {
  String id
}

class Team {
  String id
  Company company
  String companyId

  static mapping = {
    company       attr: "company"    // optional
    companyId     attr: "company", insertable: false, updateable: false
  }
}

Please note that I'm using GORM for MongoDB, which (citing the manual) tries to be as compatible as possible with GORM for Hibernate, but requires a slightly different implementation.

However I found out (by trial&error) that GORM for MongoDB doesn't support a similar solution, as it seems only one property at a time can be mapped to a MongoDB document property.
In particular the last property in alphabetical order wins, e.g. companyId in my example.


I figured out a way to make the whole thing work, I'm posting my own answer below.

Upvotes: 0

Views: 290

Answers (2)

ilPittiz
ilPittiz

Reputation: 754

(Follows the edit to my question above)

I defined a custom mapping, and made use of Grails transients by also defining custom getter and setter for team's company.

class Company {
  String id
}

class Team {
  String id
  Company company
  String companyId

  static mapping = {
    companyId     attr: "company"    // match against MongoDB property
  }

  static transients = [ 'company' ]  // non-persistent property

  Company getCompany() {
    return Company.get(companyId)
  }
  void setCompany(Company company) {
    companyId = company.id
  }

}

Upvotes: 0

Lonyui
Lonyui

Reputation: 101

given a non-insertable non-updateable column "companyId" in domain class

class Company {
  String id
}

class Team {
  String id
  Company company
  Long companyId
  static mapping = {
    company               column:"companyId"
    companyId               column:"companyId",insertable: false,updateable: false
  }
}

Upvotes: 1

Related Questions