简体   繁体   English

Hibernate:以一对多关系查询对象列表

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

I have the following one-to-many relationship between a User and multiple TvShows: 我在一个用户和多个TvShow之间具有以下一对多关系:

@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: 其中TvShow.java是:

@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. 我想要一个方法,当给定一个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. 但这只会返回与我作为参数传递的userId具有相同ID的TvShow。

The database is generated completely by Hibernate and looks like this: enter image description here 该数据库完全由Hibernate生成,如下所示: 在此处输入图像描述

I know this should be a simple query but I'm at a loss! 我知道这应该是一个简单的查询,但我很茫然!

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 . 下一个与mappedBy的用法有关。 You should define the name of the java property that the set maps to, like so: 您应该定义集合映射到的java属性的名称,如下所示:

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

Here user is the property that we mapped in the previous step. 这里的user是我们在上一步中映射的属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM