在 Hibernate 中進行聯表查詢可以使用 HQL(Hibernate Query Language)、Criteria 查詢、Criteria API 或者 SQL 查詢。
String hql = "SELECT e FROM Entity1 e JOIN e.entity2 e2 WHERE e2.property = :value";
Query query = session.createQuery(hql);
query.setParameter("value", value);
List<Entity1> results = query.list();
Criteria criteria = session.createCriteria(Entity1.class);
criteria.createAlias("entity2", "e2");
criteria.add(Restrictions.eq("e2.property", value));
List<Entity1> results = criteria.list();
CriteriaBuilder cb = session.getCriteriaBuilder();
CriteriaQuery<Entity1> query = cb.createQuery(Entity1.class);
Root<Entity1> root = query.from(Entity1.class);
Join<Entity1, Entity2> join = root.join("entity2");
query.select(root).where(cb.equal(join.get("property"), value));
List<Entity1> results = session.createQuery(query).getResultList();
String sql = "SELECT e.* FROM entity1 e JOIN entity2 e2 ON e.entity2_id = e2.id WHERE e2.property = :value";
SQLQuery query = session.createSQLQuery(sql);
query.addEntity(Entity1.class);
query.setParameter("value", value);
List<Entity1> results = query.list();
以上是在 Hibernate 中進行聯表查詢的幾種常用方法,根據具體需求和習慣選擇合適的方法來進行查詢。