user3250123
user3250123

Reputation: 25

Hibernate - How to eagerly load lazy fields?

I have a entity with multiple lazy fields -

@Entity 
public class Account implements Serializable {
    @OneToMany(mappedBy = "accountIdfk", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Address> addresses;
    .....
}

In some scenarios, I need to load addresses eagerly. Normally we call below query to fetch the entity -

dataStore.get().type(clazz).pk(id).execute();

Is there a way, we can pass any additional parameter or something in the above query to load the addresses at runtime?

Upvotes: 1

Views: 1950

Answers (2)

MartinBG
MartinBG

Reputation: 1648

In addition to solutions in @SternK's answer, you could use Spring Data JPA @Query, @NamedQuery or @NamedNativeQuery.

Here's a @NamedQuery example:

@Entity 
@NamedQuery(name = "Account.findAccountWithAddress",
        query = "SELECT a FROM Account a LEFT JOIN FETCH a.addresses AS addr WHERE a.id = :id")
public class Account implements Serializable {
    @OneToMany(mappedBy = "accountIdfk", fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
    private List<Address> addresses;
    .....
}

@Repository
public interface UserRepository extends JpaRepository<Account, Long> {

    Optional<Account> findAccountWithAddress(Long id);
}

Upvotes: 1

SternK
SternK

Reputation: 13041

You can use dynamic fetching via queries (JOIN FETCH):

Account account = entityManager.createQuery(
    "select a " +
    "from Account a " +
    "left join fetch a.addresses " +
    "where a.id = :id",
    Account.class)
.setParameter( "id", id)
.getSingleResult();

Also you can use dynamic fetching via JPA entity graph. More details you can find by the same reference.

Upvotes: 1

Related Questions