using enum list as parameter in HQL query

2019-06-16 11:56发布

问题:

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;

回答1:

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.



回答2:

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.