且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Hibernate HQL用于连接非映射表

更新时间:2022-10-16 11:14:40

在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 = ?