Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate HQL for joining non-mapped tables

Tags:

hibernate

hql

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 I'm building a KursDao that will have a method to fetch a list of Kurs by the kategoriId, but I'm 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 doesn't work and I can't get anything like this to work. I do not want to create a 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 that I will only get the Kurs that is in the correct Kategori?

like image 782
user829237 Avatar asked Jan 30 '12 18:01

user829237


1 Answers

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 = ?
like image 159
axtavt Avatar answered Sep 19 '22 10:09

axtavt