Hibernate: Projection of a collection returns ArrayIndexOutOfBoundsException
Asked Answered
H

1

6

I'm trying to get a partial object back using projection in hibernate, like this:

Movie class:

@Table(name = "Movies")
public class Movie extends Entity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;

@Column(name = "title")
private String title;

@OneToMany(cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
@JoinTable(name = "Movie_Genre", joinColumns = {@JoinColumn(name = "movieId")}, inverseJoinColumns = {@JoinColumn(name = "genreId")})
private List<Genre> genres;

When the user then goes to htp://localhost:8080/api/movies?fields=genres this is called:

Movie DAO:

Criteria cr = getCurrentSession().createCriteria(Movie.class);
ProjectionList projectionList = Projections.projectionList();
projectionList.add(Projections.property("genres"), "genres");
cr.setProjection(projectionList);
cr.setResultTransformer(Transformers.aliasToBean(Movie.class));
return cr.list();

But this returns:

java.lang.ArrayIndexOutOfBoundsException: 0
org.hibernate.loader.criteria.CriteriaLoader.getResultRow(CriteriaLoader.java:166)

Hibernate Query:

select this_.id as y0_ from Movies this_

Projections do not work when you want to project a collection...

Can somebody tell me what to do? How can this be fixed?

Thanks in advance!

Handclasp answered 31/3, 2013 at 8:30 Comment(4)
I can't figure out what are you trying to query.Circumferential
The movie class had id, title, genres,... But I only want to get genres. If I do this with title, it's OK. With genres I get this ArrayIndexOutOfBoundsException.Handclasp
Still not clear: you need all movies that have some genre? Or all genres of a movie?Circumferential
I need a list of movies where every movie has his own list of genres.Handclasp
P
0

The difference is that for title you actually have a field in the Movies entity. For the collection this cannot work since the database table has no field "genres". Rather there is an entity called "Movie_Genre" that is actually having foreign key fields to Movies and Genres.

So on database level there is no field for "genres" such that the basically only the Exception is a bit misleading. The Exception is thrown in "applyLocks" in CriteriaLoader and as the database dialect could not find a column for "genres" there are actually no columns in the returned result.

Which exact version of Hibernate are you using?

Why are you using projections and not just an Restrictions.in?

Pellagra answered 2/9, 2014 at 10:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.