Search code examples
javahibernatejpaormhibernate-mapping

Hibernate: Eager Fetch Only Specified Fields


Is there a way to specify the only fields to be eagerly fetched in hibernate/JPA @ManyToOne - FetchType.EAGER?

Something like:

@ManyToOne(fetch=FetchType.EAGER, eagerFields={"id","name"})
private Company company;

Solution

  • The JPA 2.0 specification does not define the possiblity you are trying to achieve as @ManyToOne annotation is defined as follows (see section 11.1.26 of the JPA 2.0 specification):

    public @interface ManyToOne {
        Class targetEntity() default void.class;
        CascadeType[] cascade() default {};
        FetchType fetch() default EAGER;
        boolean optional() default true;
    }
    

    What you can do to achieve eager loading only for selected fields, is possible if you specify @Basic(fetch = FetchType.LAZY) for the fields of Companyentity you want to load lazily; BUT that is not encouraged for fields other than association fields because it depends on the mercy of the provider implementation as the following extract shows:

    The EAGER strategy is a requirement on the persistence provider runtime that data must be eagerly fetched. The LAZY strategy is a hint to the persistence provider runtime that data should be fetched lazily when it is first accessed. The implementation is permitted to eagerly fetch data for which the LAZY strategy hint has been specified. In particular, lazy fetching might only be available for Basic mappings for which property-based access is used.