Hibernate HQL for joining non-mapped tables

2019-04-29 09:32发布

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?

标签: hibernate hql
4条回答
做个烂人
2楼-- · 2019-04-29 09:32

Since Hibernate 5.1 you can JOIN mapped entities without association.

So, this should work now:

SELECT k from Kurs as k 
    JOIN KursKategori kk ON k.kursId = kk.kursId AND kk.kategoriId = ?
查看更多
乱世女痞
3楼-- · 2019-04-29 09:43
getHibernateTemplate().find("from Kurs as k INNER JOIN KursKategori kk ON k.kursId = kk.kursId AND kk.kategoriId = ?", kategoriId);

You cannot make HQL query on KursKategori , a table which is not mapped in hibernate..

Either you can run sql query through hibernate template or a query something like this

select kurs from kategori k join fetch k.kursList where k.kategoriId = ?
查看更多
我命由我不由天
4楼-- · 2019-04-29 09:44

You could create a query like this and will work.

from Kurs k, KursKategori kk where k.kursId = kk.kursId AND kk.kategoriId = ?
查看更多
来,给爷笑一个
5楼-- · 2019-04-29 09:56

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 = ?
查看更多
登录 后发表回答