Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL select on embedded map

I want to use (searchable) localization in my models, and i came up with the following model:

@Entity
public class Category {
    ...
    @ElementCollection
    //key = language code (e.g. 'en') and value = localized label
    private Map<String, String> name;
    ...
}

What I want to do no is to query for categories which contain an caseinsensitive needle in a particular localization (e.g. with '%abc%' in their english name)

I tried something like

from Category where name.key = :locale and lower(name.value) like :text

but that fails with a cannot dereference scalar collection element exception.

Now the hibernate docu says, i have to use elements() and indices() for values and keys. For the key this would be easy using :locale in indices(name), but how can i then match a part of the value of this locale in an caseinsensitive manner?

And just in case this is not doable with hql with my model, how else could i model searchable localization?

like image 551
Flo Avatar asked Jan 12 '13 17:01

Flo


1 Answers

I finally came up with the following solution (actually I am pretty sure it would also work using plan maps instead of the embeddable object)

@Entity
public class Category {
    ...
    @ElementCollection
    @CollectionTable(name = "locale_category_name", joinColumns=@JoinColumn(name="id"))
List<Localization> name;
    ...
}

@Embeddable
public class Localization {
    @NotNull
    public String locale;
    @NotNull
    public String label;
}

and the query (using join ... with ...)

from Category c join c.name l with (l.locale = :locale and lower(l.label) like :text)

Edit: Actually i was unable to get it to work with a Map, so I am using the @Embeddable solution after all

like image 172
Flo Avatar answered Nov 07 '22 13:11

Flo