Card 03/ 06
Spring Data Example: @Query for a Join a Method Name Cannot Express
When two entities have no mapped relationship, you write the JPQL yourself.
@Query lets a repository method carry the query it runs, written in JPQL, instead of deriving it from the method's name. It is the tool for queries the naming convention cannot express, and the most common is a join between two entities that have no mapped relationship.
A derived name can follow an association that the entity (the class mapped to a table) declares: findByDriverName works when RideEntity has a driver field pointing at a DriverEntity. When there is no such field, a name has nothing to follow, and the join has to be written out:
interface RideJpaRepository extends JpaRepository<RideEntity, Long> {
@Query("select r from RideEntity r join DriverEntity d on d.id = r.id where d.name = ?1")
List<RideEntity> findByDriverName(String name);
}@Query join found 1 ride(s) for driver Alex, id=1The example joins on matching ids to keep it small; a real schema would join on the ride's driver column. ?1 refers to the method's first parameter by position.
JPQL is written against entities and their fields, not table and column names, which keeps it portable across the databases Hibernate supports. So reach for @Query when a name cannot say what you need, and prefer a derived name whenever one can.
← → move through sections and cards