DEV Community

Muhaimin Mukammel
Muhaimin Mukammel

Posted on

JPA Queries : Two rules for Naming Derived JPA Queries

Once, during developing a personal project I suddenly came across a weird error :

No property 'productId' found for type 'Inventory'
Enter fullscreen mode Exit fullscreen mode

I was clueless. My IDE's suggestion fixed the error. But the fix is also weird, it renamed the method from findByProductId(...) to findByProductProductId(...).

Why the extra product? So, I started researching about derived query naming and found out exactly why it's named that way.

Two rules that apply to two different scenarios for naming a JPA Query :

i. the property is directly on the entity :

Pattern : findBy + PropertyName

Example :

// Product repository, searching by its own productId field
Optional<Product> findByProductId(UUID productId);
Enter fullscreen mode Exit fullscreen mode

ii. the property lives behind a relationship :

Pattern : findBy + RelationshipName + PropertyName

Example :

// Inventory has a @ManyToOne Product product; Product has productId
List<Inventory> findByProductProductId(UUID productId);
Enter fullscreen mode Exit fullscreen mode

Rule of Thumb :
Direct property → findByX.
Property behind a relationship → findByRelationX.

Top comments (0)