简体   繁体   中英

Hibernate: Multiple select queries made by Hibernate for Fetch mode Eager

I have just started using Hibernate in my application. Also I'm using JPA repository for using custom query. I have multiple entities which have relationships between them. I have used Fetch mode as 'EAGER' on the join column and also using Cache. I observed that Hibernate is making multiple select queries to fetch each entity and not doing it in a single query.

Below is an entity:

@Entity
@Table(name = "entity_a")
public class EntityA implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    ...

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "entity_a")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<EntityB> entityB = new HashSet<>();

I'm fetching my entity as below, using JPA custom queries:

EntityA entityA = entityARepository.findOneById(id);

Hibernate issues a select query for the above statement.

Whenever I do a entityA.getEntityB() it issues another select statement on EntityB. How to avoid this. How can I get both entities in a single select using Hibernate?

Does EntityB contain a field named entity_a ? The name should be exactly as declared in the mappedBy attribute.

In general, JPA providers are required to honor the FetchType.EAGER mode. This seems to be a misconfiguration issue. Even so, while the JPA provider is required to load eager associations eagerly, there is no guarantee it will be done in a single query. There is a Hibernate-specific annotation that can be used as a hint: @Fetch(FetchMode.JOIN) . Try it out and see if it works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM