简体   繁体   中英

JPQL query with many-to-many relationship

We have 2 entities Technology and Project with a Many-to-Many relationship, which are linked with an additional reference table.

technologies
 id      name
1000 | digging
2000 | drilling

projects
id    name
10 | London
20 | Madrid

technologies_projects
tech_id     project_id
1000     | 10
2000     | 10
1000     | 20

I can retreive Technology from db with such a query:

@Query("select t from Technology t left join fetch t.projects")
List<Technology> findAll();

JPQL query with left join fetch clause must be used to retreive Technology with collection of projects to avoid lazy initialization exception.

The question is: How must the query be modified do get the list of technologies, used in a certain project? (the query findAllByProject(10) must return technologies 1000 and 2000).

I cannot use native SQL query here because I need join fetch to get collection of projects.

By adding a where clause on project entity.

@Query("select t from Technology t left join fetch t.projects p where p.id=10")
List<Technology> findAllByProject10();

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