4
votes

I want to persist a List<String> field into a single VARCHAR column using Grails with GORM and Hibernate. I have written a Hibernate custom type but cannot figure out how to get GORM/Hibernate to treat the list field as persistent:

class User {
    List<String> listOfStrings
    static mapping = {
        listOfStrings(type: StringListType, length: 512)
    }
}

The 'listOfStrings' mapping is ignored. Any ideas? For now I have worked around the problem using an extra String field and a set/get to encode and decode the List.

2
can't you use the @Type(..) annotation?Bozho

2 Answers

2
votes

I haven't written custom types before, but one thought I'd have for you is to make listOfStrings a transient variable, and have an event handler to marshall and unmarshall the list of strings for you. E.g. onLoad could do a listOfStrings = internalVarName.split(), and onUpdate could do internalVarName = listOfStrings.join(' ').

Another idea would be to wrap List of Strings into your own type, as GORM may have special handling for associations that includes specific code for types. I don't know that for a fact, just speculating.

0
votes

I think a good approach here is to rely on some existing third party libraries that already implement the Scanner/Valuer interface gorm needs for custom data types so you can do something like this:

import (
  "github.com/lib/pq"
)

type Post struct {
  Tags   pq.StringArray `gorm:"type:text[]"`
}

this snippet is similar to code from gorm docs for custom data types found here https://gorm.io/docs/data_types.html which allows you to take advantage of an existing a highly supported postgres driver for go.