5

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.