Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using enum list as parameter in HQL query

I have an entity called Band with a attribute List<Genres> genres, Genres is a ENUM with the following values: ALTERNATIVE_ROCK("Alternative Rock"), CLASSIC_ROCK("Classic Rock"), HARD_ROCK("Hard Rock"), HEAVY_METAL("Heavy Metal"),PROGRESSIVE_ROCK("Progressive Rock");

I'm trying to create a method that returns a List<Band> using an List<Genres> as parameter using HQL, something like:

public List<Band> listBandsPerGenres(List<Genres> genres);

But i'm receiving some errors with HQL queries that i'd tried?

Above some hql queries that i've tried...

Query q = getSession().createQuery("SELECT b FROM Band b JOIN FETCH b.genres g WHERE g IN (?)");
        q.setParameter(0, genres);
        return q.list();

returns an error saying that an ArrayList cannot be cast to Enum...

or...

"SELECT b FROM Band b JOIN FETCH b.genres g WHERE g.value IN (?)"

returns an error like : dereference scalar collection element ENUM

property genres mapping, entity Band...

    @Basic(optional=false)
    @Enumerated(EnumType.STRING)
    @ElementCollection(targetClass=Genres.class)
    @CollectionTable(name="banda_generos", joinColumns=@JoinColumn(name="id_banda", nullable=false))
    private List<Genres> genres;
like image 940
Bruno Santana Avatar asked Dec 31 '14 02:12

Bruno Santana


2 Answers

This works for Hibernate 4

    Query q = s
            .createQuery("SELECT b FROM Q27715453$Band b JOIN b.genres g WHERE g IN (:genres)");
    q.setParameterList("genres", Arrays.asList(Genres.ROCK, Genres.CLASSIC));
    System.out.println(Arrays.toString(q.list().toArray()));

Check that the method Query#setParameterList is used instead of Query#setParameter, also it's used g insted of g.value.

like image 129
Arturo Volpe Avatar answered Sep 23 '22 18:09

Arturo Volpe


I don't think you can do that. According to JPA spec (section 4.6.9. page 185) lists aren't supported as left-side operand with IN expression.

like image 30
Predrag Maric Avatar answered Sep 23 '22 18:09

Predrag Maric