Search code examples
javamysqlhibernatehql

Hibernate: Query list of objects in one-to-many relationship


I have the following one-to-many relationship between a User and multiple TvShows:

@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id", updatable = false, nullable = false)
private int userId;

@OneToMany(mappedBy = "tvShowId", fetch = FetchType.EAGER)
private List<TvShow> favourites;
}

where TvShow.java is:

@Entity
@Table(name = "tvshows")
public class TvShow {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", updatable = false, nullable = false)
private int tvShowId;

@OneToMany(mappedBy = "seasonId", fetch = FetchType.EAGER)
private List<Season> seasons;
}

I want a method that would return a List containing the favourite tv shows when given a userId.

So far I have:

@Query("SELECT t FROM TvShow t WHERE t.id = :userId")
public List<TvShow> getFavourites(@Param("userId") int userId);

but this just returns the TvShow that has the same Id as the userId that I've passed as a parameter.

The database is generated completely by Hibernate and looks like this: enter image description here

I know this should be a simple query but I'm at a loss!


Solution

  • You have at least a couple of problems in your code.

    Firstly, you are not defining the relation in the other entity. That is, you should tell to the TV show about the user if you are going to model the relation between entities:

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id", nullable=false)
    private User user;
    

    The next is related to the usage of mappedBy. You should define the name of the java property that the set maps to, like so:

    @OneToMany(mappedBy = "user", fetch = FetchType.EAGER)
    private List<TvShow> favourites;
    }
    

    Here user is the property that we mapped in the previous step.