简体   繁体   中英

Eagerly fetching a lazy-loaded clob with hibernate

In a spring boot app using hibernate with an oracle database (and hibernate-enhance-maven-plugin to enable lazy-loading of lobs), I have a class Category with a lazy loaded collection of Value .

@Entity
@NamedEntityGraph(name = "Category.full",
        attributeNodes = @NamedAttributeNode(value = "values", subgraph = "categoryValue"),
        subgraphs = {
            @NamedSubgraph(name = "categoryValue", attributeNodes = {
                    @NamedAttributeNode("children"), @NamedAttributeNode("detail")
            })
        })
public class Category {

...

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "type")
    @OrderBy("sequence")
    private Set<Value> values = new HashSet<>();

...

}

Value has a lazy-loaded collection children , and a lazy-loaded clob detail .

@Entity
public class Value {

...

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "parent")
    @OrderBy("sequence")
    private Set<Value> children = new HashSet<>();

    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Column(name = "Detail")
    private String detail;

...

}

When using this entity graph to fetch a full category, values and children are joined in the initial query, but detail is not fetched, and an individual query is sent for each value, which is inefficient as most of these fields are empty.

Is there any way to fetch this field in bulk when fetching the full category while still having it lazy load by default?

You can use Criteria Query to achieve your requirement.

@Autowired
private EntityManager em;


CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Value> criteria = builder.createQuery(Value.class).distinct(true);
Root<Value> value = criteria.from(Value.class);
// Add below code to eagerly fetch detail to avoid multiple query
value.fetch("children", JoinType.INNER);
criteria.select(value);

You can also read more about criteria Query here

https://www.baeldung.com/spring-data-criteria-queries

https://www.baeldung.com/jpa-join-types

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