Hibernate中如何实现多表关联查询?代码举例讲解

在Hibernate中,多表关联查询可以通过HQL或SQL的JOIN语句实现。主要有以下几种方式:

  1. HQL内连接查询:
String hql = "from Order o inner join o.customer c where c.name = ?";
Query query = session.createQuery(hql);
query.setParameter(1, "John");
List<Order> list = query.list();
  1. HQL左外连接查询:
String hql = "from Order o left join o.customer c where c.name = ?";  
  1. SQL内连接查询:
String ``` = "SELECT * FROM t_order o INNER JOIN t_customer c ON o.customer_id = c.id WHERE c.name = ?";
Query query = session.createSQLQuery(```);
query.setParameter(1, "John");
List<Object[]> list = query.list(); 
  1. SQL左外连接查询:
String ``` = "SELECT * FROM t_order o LEFT JOIN t_customer c ON o.customer_id = c.id WHERE c.name = ?";  
  1. 复杂关联查询:
  • 可以通过多表关联实现更复杂的关联查询,如三表关联等。
String hql = "from Order o inner join o.customer c inner join c.company com where com.name = ?";