Spring JPA 延迟加载@OneToOne 实体不起作用

Spring JPA Lazy loading @OneToOne entities doesn't work

我在延迟 OrderEntity 对象加载 BillingAddress 时遇到了问题。我已经看到围绕这个问题提出了很多问题并遵循了说明,包括添加 optional = false 但是 BillingAddress 仍然会在我 findById 一个 OrderEntity.

时加载

这些是我的实体(为了这个问题减少了):

OrderEntity

@Entity
@Table(name = "orders", schema = "glamitoms")
public class OrderEntity {

    @Id
    @Column(name = "id")
    private int id;

    @OneToOne(mappedBy = "order", cascade = CascadeType.ALL, fetch = FetchType.LAZY, optional = false)
    private BillingAddressEntity billingAddress;

}

BillingAddressEntity

@Entity
@Table(name = "billing_address", schema = "glamitoms")
public class BillingAddressEntity {

    @Id
    @Column(name = "order_id")
    private int id;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    private OrderEntity order;
}

测试控制器

@RestController
public class TestController {

    private OrdersDAO ordersDAO;

    @Autowired
    public TestController(OrdersDAO ordersDAO) {
        this.ordersDAO = ordersDAO;
    }

    @GetMapping("/test")
    public void test() {
        OrderEntity orderEntity = ordersDAO.findById(1).get();
    }
}

OrdersDAO

@Repository
public interface OrdersDAO extends JpaRepository<OrderEntity, Integer> {
}

table billing_address 有FK引用命令。我读过相互矛盾的答案,说添加 optional = false 应该延迟加载实体,但对我来说,这似乎不起作用。我在这些实体中遗漏了什么吗?

看看 Vlad Mihalceas 的文章 The best way to map a @OneToOne relationship with JPA and Hibernate

如那里所述,解决方案之一是放弃父方的关系...

@Transient
private BillingAddressEntity billingAddress;

并使用共享 ID 手动加载 BillingAddressEntity

if (order.billingAddress == null) 
{
   order.billingAddress = entityManager.find(BillingAddressEntity.class, order.id);
}


另一种方法是删除共享密钥,改用外键字段并将关系标记为 @ManyToOne。不过,这将牺牲 OneToOne 约束检查。

@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "billing_address_id")
private BillingAddressEntity billingAddress;


然后还有字节码增强功能,可让您将其设为 @LazyToOne(LazyToOneOption.NO_PROXY) 关系。不过我帮不了你,因为我自己从来没有这样做过。