Hibernate进行了太多查询

时间:2017-05-26 08:11:27

标签: postgresql hibernate spring-boot orm jhipster

我的应用程序出现了性能问题。

我有三个实体,其关系如下:

one Order => many OrderLines => Many Cards

来自数据库的实体加载花费了太多时间,orderLines加载了急切的加载,而加载了延迟加载的卡。为了让应用程序流畅,需要延迟加载。

我需要为一个案例配置急切加载,我需要帮助才能完成。

我正在使用jhsipster stack:spring-boot with JPA

我试着编写Hql查询

@Query(value = "from Order as order "
        + "inner join order.orderLines as orderLines "
        + "inner join orderlines.cards gc "
        + "where order.id= :order")
Order findWithDependencies(@Param("order")Long order);

我没有错误:意外的令牌顺序(第2行)

我尝试使用原生查询

@Query(value = "select * "+ 
        "from order_table ot "+
        "left join order_line ol ON ot.id = ol.order_id "+
        "left join  giftcard gc ON gc.orderline_id = ol.id "+
        "where ot.id=:order", nativeQuery= true)
Order findWithDependenciesNative(@Param("order")Long order);

但是当我做的时候

orderLine.getCard()

从代码中,Hibernate仍然会进行查询以从数据库中获取数据,这会导致我的性能问题。

实体的必要代码:

public class Order implements Serializable {
    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
    @JoinColumn(name = "order_id", nullable = false)
    @Size(min = 1)
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    @JsonProperty("detail")
    @Valid
    private List<OrderLine> orderLines = new ArrayList<>();
}
public class OrderLine extends AbstractAuditingEntity implements Serializable, Comparable {
    @OneToMany
    @JoinColumn(name = "orderline_id")
    @JsonIgnore
    @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private Set<Giftcard> giftcards = new HashSet<>();
}

public class Giftcard extends AbstractAuditingEntity implements Serializable, Comparable {
    @ManyToOne(optional = true)
    @JoinColumn(name= "orderline_id")
    @JsonIgnore
    private OrderLine orderLine;
}

我的代码实际上是

{
    Order order = orderRepository.findWithDependenciesNative(linkFile.getOrder());
    //Some code
    List<OrderLine> orderLines = order.getOrderLines();
    orderLines.sort(Comparator.comparing(OrderLine::getId));
    for (OrderLine orderLine : orderLines) {
        Stream<Card> cards = orderLine.getCards().stream().sorted(Comparator.comparing(Card::getCardNumber));
        for (Card card : cards.collect(Collectors.toList())) {
        //Some code
        }
    }

问题在于第二个foreach,因为每个卡hibernate都执行两个查询,而带有join的请求不会加载像eager配置这样的数据。你有意帮助我吗?

非常感谢

1 个答案:

答案 0 :(得分:2)

使用&#34; 加入提取&#34;避免延迟加载。 A&#34; fetch&#34; join允许使用单个select将关联或值集合与其父对象一起初始化。这在集合的情况下特别有用。它有效地覆盖了关联和集合的映射文件的外连接和延迟声明。 请参阅有关加入提取的详细信息:Difference between JOIN and JOIN FETCH in Hibernate

@Query("Select order from Order as order "
        + "inner join fetch order.orderLines as orderLines "
        + "inner join fetch orderlines.cards gc "
        + "where order.id= :order")
Order findWithDependencies(@Param("order")Long order);