HQL查询返回没有结果
问题描述:
我是HQL初学者(并且在所有休眠状态下)。我需要一个简单的多对多关系帮助:HQL查询返回没有结果
视频 - video_category - 类别
Category.java
@Entity
public class Category {
@Id
@GeneratedValue
private int id;
@Size(min = 3, max = 20, message = "3-20 chars!")
private String name;
@ManyToMany(mappedBy = "categories")
private List<Video> videos;
//Getters and setters
Video.java
@Entity
public class Video {
@Id
@GeneratedValue
private int id;
private String url;
private Date publishDate;
@ManyToOne(cascade = CascadeType.REMOVE)
@JoinColumn(name = "user_id")
private User user;
@NotEmpty
@ManyToMany(cascade = CascadeType.REMOVE)
@JoinTable(name = "video_category", joinColumns = @JoinColumn(name = "video_id"), inverseJoinColumns = @JoinColumn(name = "category_id"))
private List<Category> categories;
个而这个查询没有给我结果
Query query = sessionFactory
.getCurrentSession()
.createQuery(
"from Video vid inner join vid.categories cat where vid.id = :category");
query.setParameter("category", category);
如果我只发送.createQuery("from Video")
- 它给了我所有视频(所以DB连接是罚款)。 Category
a video_category
表也有一些数据。我想,连接表或其他地方会出现错误。
编辑:
我试图实现走表video_category
,看看那里category_id
。在SQL中,像这样:select * from Video join video_category on Video.id=video_category.video_id where category_id = 2
答
您正在使用视频的别名,而不是使用类别的别名。使用连击名字,它应该变得更加明显:
select video
from Video video
inner join video.categories category
where category.id = :categoryId
'ug'(为什么这到底是不是'video'它这样命名)是视频的别名。并且您正在尝试查找ID等于参数'category“的视频。要么你为这个参数选择了一个非常奇怪的名字,该名称应该被命名为'videoId',或者它实际上是一个类别的ID,并且试图找到具有该类别ID的视频是非常奇怪的。你想达到什么目的?什么是'类别'?你为什么不使用session.get(Video.class,id)? –
对不起,我会编辑它。这是一个ManyToMany关系,我试图加入table'video_category'并在那里寻找'category_id'。在SQL中,它是这样的:'select * from Video join video_category on Video.id = video_category.video_id where category_id = 2'。 – Pivoman
然后你需要'where u.id =:category'。 'ug'是视频的别名。 'u'是类别的别名。一切都会更清晰,命名方式很好:'从视频视频内连接video.categories类别中选择视频,其中category.id =:catagoryId'。 –