9

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;
4
  • 2
    what were those queries you tried, and what were the corresponding errors? Commented Dec 31, 2014 at 2:40
  • Please add the annotations of the List<Genres>, it's important to see if it is EnumType.String or the default. Commented Dec 31, 2014 at 2:47
  • i'm using this ENUM like ENUMTYPE.STRING Commented Dec 31, 2014 at 2:50
  • Please add the entire property with all the annotations (the genre property) Commented Dec 31, 2014 at 3:16

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks!!! it worked perfectly!!! Happy new year and keep on rocking with Java uahauhauhauhauah !!
1

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.

1 Comment

like @AVolpe said in the answer below... it works with Hibernate 4 with using setParameterList method

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.