我是HQL的初学者(并且完全是休眠)。我需要一个简单的 ManyToMany 关系的帮助:
视频 - 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
video_category
个表也有一些数据。我认为,加入桌子或某个地方会有错误。
编辑:
我试图进入表video_category
并查看category_id
。在这样的SQL中:select * from Video join video_category on Video.id=video_category.video_id where category_id = 2
答案 0 :(得分:1)
您正在使用视频的别名,而不是使用该类别的别名。使用击球手名称,它应该变得更加明显:
select video
from Video video
inner join video.categories category
where category.id = :categoryId