有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java加入条件查询出现错误“无法定位属性”

我有两张桌子和两门课。我必须连接两个表并获得特定字段

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]的属性” 有人能帮我加入吗。我知道我把这两张桌子放在一起是做错了什么


共 (1) 个答案

  1. # 1 楼答案

    我将改变以下几点:

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

    必须指明在参数类型(Set)中定义的目标类的参数

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

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

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

    或者

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

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