Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grails: Data binding custom hibernate types with multiple columns

I'm using custom hibernate types with Grails (http://grails.org/doc/2.3.x/guide/GORM.html#customHibernateTypes) and I'm mapping the type to multiple columns. However, I'm a little stuck on figuring out how to do data binding on these custom types. I can use a @BindUsing annotation, however, I have only one property and multiple columns.

For example here's a groovy class (that will have a custom type that's created using a properly defined CustomDataUserType class):

class CustomData
{
  String field1
  String field2
}

And here's a domain model that has this class as a property

class DomainModel
{
  static mapping = {      
    customData type: CustomDataUserType, {
        column name: "field1"
        column name: "field2"
    }

  @BindUsing { obj, source ->
    // The source contains a field/property called customData (otherwise
    //   this BindUsing closure doesn't get called) however, I need two
    //   values
  }
  CustomData customData
}

My problem is that inside the BindUsing closure the source contains one value, a property called customData. However, I need two values to recreate the custom object. How is this problem usually solved?

like image 829
Harry Muscle Avatar asked Nov 10 '22 11:11

Harry Muscle


1 Answers

The BindUsing closure is passed the current object and a map the map is Source in your code example. If you had field1 and field2 being passed in the map you could easily put those into your CustomData type.

So for example POSTing this JSON to a controller expecting a DomainModel

{
  field1: 'test',
  field2: '1'
}

With the following @BindUsing in the DomainModel

 @BindUsing { obj, source ->
    CustomData customData = new CustomData(field1: source['field1'],field2: source['field2'])
    return customData
  }
  CustomData customData

That should correctly create your custom object via data binding.

like image 197
Jeff Beck Avatar answered Nov 15 '22 05:11

Jeff Beck