join in criteria query giving error "Unable to locate Attribute "

Viewed 734

I have two tables student and courses . I have to join two table and get specific fields .

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;
   }
 

if I query :-

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)));

I am getting "Unable to locate Attribute with the the given name [student] on this ManagedType[Parent]" Can some one help me with join .I know i am doing some thing wrong in joining these two tables.

1 Answers

I would change the following:

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

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

You have to indicate the parameter of the target class, which you define in the parameter type (Set ).

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

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

As above, the join parameter has to match the name of the parameter.

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

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

or

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

To use get you have to pass a String with the name of the field as a parameter, or use the metamodel (ending in an underscore)

Related