加入条件查询,给出错误“无法找到属性”

问题描述

我有两张桌子的学生和课程。我必须加入两个表并获取特定字段。

class Student extends Parent{
  
  Long id;
  @Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
  @OnetoMany(fetch = FetchType.LAZY,mappedBy = courses.student,cascade = CascadeType.ALL)
    Set<Courses> coursesList = new HashSet<>();
 }
 
 @Table(name = "courses",indexes = {
    @Index(name = "id",columnList = Courses.id,unique = true),@Index(name = "student_course_fk",columnList = "student_fk"),class Courses extends Parent{
     Long id;
     @ManyToOne
     @JoinColumn(name = "student_fk")
     Student student;
   }
 

如果我查询:-

CriteriaBuilder cb=entityManager.getCriteriaBuilder();
CriteriaQuery<Student> q = cb.createquery(Student.class);
Root<Student> c = q.from(Student.class);
Join<Student,Courses> lineJoin  = root.join("Courses",JoinType.INNER);
lineJoin.on(criteriaBuilder.equal(root.get(Courses.student),root.get(student.id)));

我得到“无法在此ManagedType [Parent]上找到具有给定名称[student]的属性” 有人可以帮我联接吗。我知道我在联接这两个表时做错了。

解决方法

我将更改以下内容:

@Repository
public interface TransDeliveryPlanningRepository extends RevisionRepository<TransDeliveryPlanning,Long,Integer>,JpaRepository<TransDeliveryPlanning,Long> {
    
    @Modifying
    TransDeliveryPlanning save(TransDeliveryPlanning transDeliveryPlanning);
}

您必须指示目标类的参数,该参数是在参数类型(Set)中定义的。

@OneToMany(fetch = FetchType.LAZY,mappedBy = courses.student,...

@OneToMany(fetch = FetchType.LAZY,mappedBy = student,...

如上所述,join参数必须与参数名称匹配。

Join<Student,Courses> lineJoin  = root.join("Courses",JoinType.INNER);

Join<Student,Courses> lineJoin  = root.join("coursesList",JoinType.INNER);

lineJoin.on(criteriaBuilder.equal(root.get(Courses.student)

lineJoin.on(criteriaBuilder.equal(root.get("student")

要使用get,您必须传递一个以字段名称为参数的String,或者使用元模型(以下划线结尾)