Is it possible to specify fetchgraph/loadgraph in SpringDataJpa @QueryHint annotation

540 views Asked by At

Is it possible somehow to specify the javax.persistence.fetchgraph or javax.persistence.loadgraph using @QueryHint in Spring Data Jpa?

I have an entity graph

@Entity
@NamedEntityGraph(
        name = "shop_with_all_associations",
        includeAllAttributes = true
)
public class Shop {    
    @JoinColumn(name = "shop_id")
    @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
    private List<Member> members = new ArrayList<>();
}

And the corresponding method in the repository

@Repository
public interface ShopRepository extends JpaRepository<Shop, Integer> {
    @QueryHints({@QueryHint(name = "javax.persistence.fetchgraph", value = "shop_with_all_associations")})
    List<Shop> getAllWithQueryHintBy();
}
2

There are 2 answers

0
Max On

No, it's not possible. You can check your log and see the next warning when calling the method

o.h.q.internal.AbstractProducedQuery     : The javax.persistence.fetchgraph hint was set, but the value was not an EntityGraph!

And in the AbstractProducedQuery class, the next code section shows, that only instances of RootGraph could be treated as EntityGraph. But our @QueryHint allow to pass only String as value.

else if ( HINT_FETCHGRAPH.equals( hintName ) || HINT_LOADGRAPH.equals( hintName ) ) {
                if ( value instanceof RootGraph ) {
                    applyGraph( (RootGraph) value, GraphSemantic.fromJpaHintName( hintName ) );
                    applyEntityGraphQueryHint( new EntityGraphQueryHint( hintName, (RootGraphImpl) value ) );
                }
                else {
                    MSG_LOGGER.warnf( "The %s hint was set, but the value was not an EntityGraph!", hintName );
                }
                applied = true;
            }
0
Archimedes Trajano On

You don't do it through @QueryHint you use the @EntityGraph annotation.

From https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.entity-graph

public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
  GroupInfo getByGroupName(String name);

}