@Entity
@Table(name="TEAM")
class Book {
int id;
string book_name;
@ManyToOne
Lib lib;
public int getId(){ return this.id;}
public void setId(int id){ this.id = id; }
public string getBook_name(){ return this.book_name;}
public void setBook_name(string book_name){ this.book_name = book_name; }
public Lib getLib(){ return this.lib;}
public void setLib(Lib lib){ this.lib = lib; }
}
class Lib {
int id;
string lib_name;
Set<book> books;
public int getId(){ return this.id;}
public void setId(int id){ this.id = id; }
public string getLib_name(){ return this.lib_name;}
public void setLib_name(string lib_name){ this.lib_name = lib_name; }
public Set<book> getBooks(){ return this.books;}
public void setBooks(Set<book> books){ this.books = books; }
}How to execute join queries in hibernate?
There are three ways:
1) SQL:
SQLQuery query = session.createSQLQuery("SELECT {b.*}, {l.*} FROM book b INNER JOIN lib l ON l.id = b.lib.id");
query.addEntity("p", Book.class);
query.addJoin("l", "b.lib");
... = query.list();2) HQL:
Query query = session.createQuery("FROM Book as b INNER JOIN FETCH b.lib as l");
... = query.list();3) Criteria
Criteria criteria = session.createCriteria(Book.class, "b");
criteria.createAlias("b.lib", "l");
... = criteria.list();