JPA Criteria Query联表查询Student与Courses报Unable to locate Attribute错误的解决
关联查询报错的核心原因
- 实体关联注解配置错误:Student的@OneToMany中mappedBy字段取值不合法,写为
courses.student,实际该字段需填写对方实体中维护关联的属性名,也就是Courses类里的student字段。 - 代码变量定义错配:代码中通过
q.from(Student.class)生成的Root对象命名为c,但后续代码使用了未定义的root变量,前后变量名不统一。 - join方法传参错误:
root.join("Courses", JoinType.INNER)中传入的是Courses的类名字符串,实际需要传入Student类中定义的关联集合属性名,也就是coursesList,join方法只能基于当前Root实体已定义的关联属性做关联。 - on条件写法错误:Criteria API会通过实体上的@JoinColumn注解自动推导两表的关联外键关系,不需要手动编写
root.get(Courses.student) = root.get(student.id)这类相等条件。同时Root.get()方法仅支持传入属性名字符串或类型安全的元模型引用,不能直接传入类的字段对象,加上Student及其父类Parent本身就没有student属性,最终触发了Unable to locate Attribute with the the given name [student] on this ManagedType[Parent]的报错。 - 注解参数配置错误:Courses类上@Index注解的columnList参数需传入字符串形式的列名,原写法
columnList = Courses.id不符合Java注解的参数要求,编译无法通过。
修正后的实现
第一步:修正实体注解错误
class Student extends Parent{ Long id; @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) // 修正mappedBy取值为Courses实体中维护关联的属性名 @OneToMany(fetch = FetchType.LAZY, mappedBy = "student", cascade = CascadeType.ALL) Set<Courses> coursesList = new HashSet<>(); } @Table(name = "courses", indexes = { // 修正columnList为字符串形式的列名 @Index(name = "id", columnList = "id", unique = true), @Index(name = "student_course_fk", columnList = "student_fk") }) class Courses extends Parent{ Long id; @ManyToOne @JoinColumn(name = "student_fk") Student student; }
注:双向关联关系中,
mappedBy标记的是外键维护方对应的属性,此处的取值必须和Courses类中@ManyToOne标注的属性名完全一致。
第二步:编写正确的Criteria查询代码
CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Student> q = cb.createQuery(Student.class); // 统一变量命名,避免前后引用错配 Root<Student> studentRoot = q.from(Student.class); // 基于Student类中定义的coursesList属性做内连接,不需要手动书写外键相等条件 Join<Student, Courses> courseJoin = studentRoot.join("coursesList", JoinType.INNER); // 如需给关联的Courses加额外过滤条件,再调用on方法即可,例如筛选学分大于2的课程: // courseJoin.on(cb.greaterThan(courseJoin.get("credit"), 2));
优化建议
- 可引入JPA元模型生成功能,用类型安全的元模型引用替代硬编码的属性名字符串,避免拼写错误导致的运行时报错,示例写法:
Join<Student, Courses> courseJoin = studentRoot.join(Student_.coursesList, JoinType.INNER); - 如果查询仅需要获取两表的部分指定字段,可调整CriteriaQuery的返回类型为自定义DTO,避免加载全量实体造成的性能损耗。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

