EntityManager em = emf.createEntityManager(); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TestStudentPo> query = cb.createQuery(TestStudentPo.class); Root<TestStudentPo> root = query.from(TestStudentPo.class); //建立關聯關係 Join<TestStudentPo, TestClassPo> join = root.join("testClassPo", JoinType.LEFT); query.select(root).where(cb.equal(join.get("classId"), "1")); List<TestStudentPo> list = em.createQuery(query).getResultList(); ------------ 這段JPA API 轉爲sql爲: ------------ SELECT a.STUDENT_ID AS STUDENT_1_2_, a.CLASS_ID AS CLASS_ID2_2_, a.COURSE_ID AS COURSE_I3_2_, a.STUDENT_NAME AS STUDENT_4_2_, a.TIME AS TIME5_2_ FROM test_student a LEFT OUTER JOIN test_class b ON a.CLASS_ID = b.CLASS_ID WHERE b.CLASS_ID =?
最重要的是這個關係要配置好sql
@OneToOne @JoinColumn(name="CLASS_ID",referencedColumnName = "CLASS_ID") private TestClassPo testClassPo;