Henryk Konsek
Henryk Konsek

Reputation: 9168

Map of other types than Strings in Grails

I created simple domain class with map within it.

class Foo {
   Map bar
}

Bar mapping will be created as sth like:

create table foo_bar (bar bigint, bar_idx varchar(255),
   bar_elt varchar(255) not null);

...as stated in http://www.grails.org/GORM+-+Collection+Types:

The static hasMany property defines the type of the elements within the Map. The keys for the map MUST be strings.

Now my question is - is it possible to create map of values other than Strings? I can achieve that using pure Hibernate (element mapping) - any ideas how to port this to Grails?

Upvotes: 0

Views: 1025

Answers (1)

olmaygti
olmaygti

Reputation: 11

I think you meant if it's possible to create map of KEYS other than Strings.

It is not possible: all keys must be Strings, while values can be whatever type you want. A way to achieve what you want is using some unique identifier for the type of class you want as key of your map.

Say you want a Map persisted in your database and say you have two instances: objectA and objectB you want to persist in your map, which name is "relationship":

relationship."objectA.toString()" = objectB

That should work. Changet toString() with hashCode(), getId() or whatever thing that gives you a unique String that identifies that object and only that, and you got it.

Upvotes: 1

Related Questions