我正在与LazyInitializationException挣扎。到目前为止,我几乎已经阅读了有关该文章的每篇文章,但是不幸的是,我没有找到解决问题的方法。这些解决方案中有许多使用EntityManager或我不使用的东西。我正在通过JPA连接我的数据库。

我有几个实体,但是问题仅在于其中两个:Order和OrderDetails。
当我从数据库对象Order获取数据时,然后尝试执行order.getOrderDetails(),然后出现以下错误:

例外:

Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.tradesystem.order.Order.orderDetails, could not initialize proxy - no Session


但是它的工作方式却相反:从OrderDetails对象中,我可以通过objectDetail.getOrder()获得Order。
而且,由于我在另一个实体中使用它,所以我不能使用Eager加载。

这是我的Order类:

@Entity
@Data
@Table(name = "orders")
public class Order {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "order_id")
private Long id;

private LocalDate date;

@OneToMany(mappedBy = "order")
private List<OrderDetails> orderDetails;

@ManyToOne
@JoinColumn(name = "buyer_fk")
private Buyer buyer;

@ManyToOne
@JoinColumn(name = "supplier_fk")
private Supplier supplier;
}


OrderDao:

@Repository("orderDao")
public interface OrderDao extends JpaRepository<Order, Long> {

@Query(value = "SELECT * FROM orders " +
        "WHERE MONTH(orders.date) = ?1 AND YEAR(orders.date) = ?2",
        nativeQuery = true)
List<Order> getMonthOrders(int month, int year);
}


和OrderDetails:

@Entity
@Data
@Table(name = "orderDetails")
public class OrderDetails {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "order_details_id")
private Long id;

private BigDecimal quantity;

private BigDecimal sum;

@ManyToOne
@JoinColumn(name = "order_fk")
private Order order;

@ManyToOne
@JoinColumn(name = "product_fk")
private Product productType;

@OneToOne
@JoinColumn(name = "order_comment_fk")
private OrderComment orderComment;
}


以@Many完成的关系默认情况下是延迟加载的,那么为什么在我执行.getOrderDetails()时不加载OrderDetails呢?

如果有任何帮助,我将不胜感激!
PS。我是乞讨者,所以,如果我没有解释足够好的东西,请不要犹豫,提出一些问题。

最佳答案

用这个

@Repository("orderDao")
public interface OrderDao extends JpaRepository<Order, Long> {

    @Query(value = "SELECT orders FROM Order orders LEFT JOIN FETCH orders.orderDetails " +
        "WHERE MONTH(orders.date) = ?1 AND YEAR(orders.date) = ?2")
    List<Order> getMonthOrders(int month, int year);
}

10-08 01:21