Hibernate HQL用于连接非映射表 [英] Hibernate HQL for joining non-mapped tables
问题描述
我有一个名为Kurs的实体:
@Entity
public class Kurs {
@I $
@GeneratedValue(strategy = GenerationType.AUTO)
private long kursId;
私人字符串名称;
// Accessors ....
}
分类:
@Entity
公共类分类{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long kategoriId;
私人字符串名称;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(name =KursKategori,joinColumns = {@JoinColumn(name =kategoriId)},inverseJoinColumns = {@JoinColumn name =kursId)})
private List< Kurs> kursList;
// Accessors ....
}
现在我正在构建一个KursDao ,这将有一个方法来获取kategoriId的Kurs列表。但我无法让加入为我工作。
习惯于SQL我通常会认为查询应该是这样的:
$ b $ $ $ $ p $ getHibernateTemplate()。find( from Kurs as k INNER JOIN KursKategori kk ON k.kursId = kk.kursId AND kk.kategoriId =?,kategoriId);
但是这不起作用,我不能得到任何这样的工作。我不想创建一个KursKategori类,因为它只是一个映射表。
有没有办法将非映射表KursKategori连接到映射表kurs,所以我只会得到正确Kategori中的Kurs?
在HQL中,您只能加入实体之间的映射关系。然而,你有这样的关系,所以你可以使用它:
select kurs from Kategori kat join kat.kursList kurs where kat.kategoriId =?
I have an entity called "Kurs":
@Entity
public class Kurs {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long kursId;
private String name;
//Accessors....
}
And also an entity called "Kategori":
@Entity
public class Kategori {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long kategoriId;
private String name;
@ManyToMany(cascade = CascadeType.ALL)
@JoinTable (name = "KursKategori", joinColumns = {@JoinColumn(name = "kategoriId")}, inverseJoinColumns = {@JoinColumn(name = "kursId")})
private List<Kurs> kursList;
// Accessors....
}
Now im building a KursDao, that will have a method to fetch a list of Kurs by the kategoriId. But im unable to get the join to work for me. Being used to SQL i would normally think the query should be like this:
getHibernateTemplate().find("from Kurs as k INNER JOIN KursKategori kk ON k.kursId = kk.kursId AND kk.kategoriId = ?", kategoriId);
But this doesnt work and i cant get anything like this to work. I do not want to create an Class of the KursKategori since it is only a mapping table anyway. Is there a way to join the non-mapped table KursKategori to the mapped table kurs so i will only get the Kurs that is in the correct Kategori?
In HQL you can only join on mapped relationships between entities. However, you have such a relationship, so that you can use it:
select kurs from Kategori kat join kat.kursList kurs where kat.kategoriId = ?
这篇关于Hibernate HQL用于连接非映射表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!