简体   繁体   中英

Complicated query with jparepository. Three tables join

I want to filter entities with next way: get distinct 10 top disciplines, which are ordered by students count(attendance) for sessions between some period of time.

  • Discipline has List<Session> sessions; //bidirectional
  • Every Session has its own List<Student> students; //bidirectional

So, Student didn't know anything about Discipline, only via Session. And I want to write using Spring JpaRepository something like:

List<Discipline> findTop10DisciplinesDistinctOrderBySessionsStudentsCountAndBySessionsBetween(Date from, Date to);

but there are some restrictions. It didn't work for me

No property count found for type Student! Traversed path: Discipline.sessions.students.

Query looks like this(mysql):

select d.*
from session as ses 
inner join    
(select st.*
from student as st 
inner join session as ses on ses.id = st.session_id
where ses.time > (curdate() - interval 30 day)
group by st.session_id
order by count(st.id) desc 
limit 10) as st2
on ses.id = st2.session_id
inner join discipline as d on ses.discipline_id = d.id

But how to add this query to jpa repository?

Derived queries, those that get created from the method name are not suitable for use cases as yours. Even if it would work it would result in an unwieldy method name. Use an @Query with JPQL or SQL query instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM