Bean
Bean

Reputation: 550

Grails Transient as a lookup

Getting my feet wet with Grails, so please bear with me...

Just wondering if this is a good use of transient, or if there's a better way.

say I have

class Author {

String name
String favoriteBook

static transients = ["favoriteBook"]

etc.

"Favorite Book" is the title from the Book table of the a book published by the author. I have a database stored procedure (function) that I want to use to do this lookup. I don't want it persisted to the database, just evaluated on the fly when the Author list (and show) is executed. For the list, ideally it is sortable as well.

Note: using Oracle datbase

This obviously is not my real world example, I am actually working on extending a legacy database, and cannot touch that structure....I have a lot of stored procedures that can be utilized. So the question remains...I want my domain class to pull down a value from the database which is the result of a stored procedure.

I find examples on the web of using transients, but not in this way...am I misusing it? How do I utilize stored procedures within g&g and GORM?

I also find example of using stored procedures, like this one http://www.craigburke.com/post/44771719252/oracle-stored-procs-in-grails but missing how to implement this in the views...

tia...

K.

Upvotes: 1

Views: 244

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

Instead of declaring it as a transient I would map it as a formula

class Author {
  String name
  String favoriteBook

  static mapping = {
    favoriteBook formula:'find_favorite_book(id)'
}

(or whatever the required SQL is to call your custom function).

Quoting from the linked documentation

Note that the formula expressed in the ORM DSL is SQL so references to other properties should relate to the persistence model not the object model.

i.e. if you need to refer to other properties in the formula then you have to use the database column names (some_property) rather than the property names (someProperty). If you don't want to have to guess the naming convention then you should consider making the property-to-column mapping explicit for any columns you want to use in the formula

static mapping = {
  someProperty column:'my_unusual_column'
}

Upvotes: 2

Related Questions