JPA or Hibernate or Spring for specifying a query for a relationship?

Is it possible to explicitly specify a query to run to collect related entities using JPA or Hibernate annotations?

Specifically, I have the following objects: Tutor, Student, and an explicit OneToOne relationship between Tutor and Student, Tutorial:

@Entity
public class Student {
  @OneToMany Collection<Tutorial> tutorials;
}

@Entity
public class Tutor {
  @OneToMany Collection<Tutorial> tutorials;
}

@Entity
public class Tutorial {
  @OneToOne Tutor tutor;
  @OneToOne Student student;
  // other data
}

      

A student can be assigned as a Homework Teacher in the Study Guide (but not a mentor who has not been assigned a student), so:

@Entity
public class Homework { 
   @ManyToOne Tutorial tutorial;
   // other data
}

      

Now I want to get all the students homework:

@Entity
public class Student {
  @OneToMany Collection<Tutorial> tutorials;

  @OneToMany Collection<Homework> homework;
}

      

But there is no Student in Homework; he has a tutorial. It's easy to express in SQL:

select a.* 
from Homework a 
join Tutorial b on (a.tutorial_id = b.id)
where b.student_id = ?student.id?

      

Can I express this using JPA or Hibernate or Spring annotations directly in the student class so that it is used when I call Student.getHomework ()?

In other words, I want:

@Entity
public class Student {
  @OneToMany Collection<Tutorial> tutorials;

  @ExplicitQuery("select Homework where Homework.student = this or something")
  @OneToMany Collection<Homework> homework;
}

      

+3


source to share


1 answer


You should be able to do this in Hibernate using a custom loader

@Entity
@NamedNativeQuery(name="customHomeworkLoader", query="select a.* from Homework a join Tutorial b on (a.tutorial_id = b.id) where b.student_id = ?", resultClass = Homework.class)
public class Student {
  @OneToMany Collection<Tutorial> tutorials;

  @Loader(namedQuery = "customHomeworkLoader")
  @OneToMany Collection<Homework> homework;
}

      



The positional parameter ( ?

) in a named query should be automatically replaced with the primary key at runtime. I have not tried this code, so I cannot guarantee that it will work, but hopefully it will give you a hint on how to proceed.

+3


source







All Articles