Dropwizard-Hibernate Lazy fetch 不偷懒

Dropwizard-Hibernate Lazy fetch is not lazy

我正在使用 Dropwizard-1.1.2 和 hibernate-5.2.8。我实现了这样的一对多关系:

父级 Table:

@TypeDefs( {@TypeDef( name= "StringJsonObject", typeClass = StringJsonUserType.class)})
@Table(name="parent_table")
@Entity
public class ParentTable {

    @Id
    @GeneratedValue(generator = "UUID")
    @GenericGenerator(
        name = "UUID",
        strategy = "org.hibernate.id.UUIDGenerator"
    )
    @Column(name = "parent_id", updatable = false, nullable = false)
    private UUID id;

    @JoinColumn(name="parent_id")
    @OneToMany(targetEntity = NotificationModel.class, cascade = {CascadeType.ALL}, fetch = FetchType.LAZY)
    private List<NotificationModel> notifications = new ArrayList<>();

    public UUID getId() {
        return id;
    }

    public List<NotificationModel> getNotifications() {
        return notifications;
    }

    public void setNotifications(List<NotificationModel> notifications) {
        this.notifications = notifications;
    }

}

通知Table

@Table(name="notifications")
@Entity
public class ReminderNotificationModel {
@Id
    @GeneratedValue
    private Integer id;

    @Column(name = "notification_id")
    @Type(type="pg-uuid")
    private UUID notificationId;

    private String message;

    @Column(name = "notification_status")
    private String notificationStatus;

    @Column(name = "scheduled_at")
    private DateTime scheduledAt;

   // getters and constructors
}

现在在我的 DAO 中,无论我尝试本机查询、标准查询还是通过 id 在父 table 上获取,它也总是给我所有的通知。是否应该延迟获取通知?

DAO

public class ReminderDao extends AbstractDAO<ReminderModel> {


    @Inject
    public ReminderDao(SessionFactory sessionFactory) {
        super(sessionFactory);
    }

    public ReminderModel getById(UUID id) {
        ReminderModel m = get(id);  // m has notifications as well
        return m;
    }
}

我正在阅读 hibernate 的 documentation,它说 Lazy 是对基本类型的提示。但是集合不是基本类型。如此懒惰应该得到尊重。我错过了什么?

LAZY is merely a hint that the value be fetched when the attribute is accessed. Hibernate ignores this setting for basic types unless you are using bytecode enhancement

"Loading the notifications of a parent lazily" 与 "not loading notifications of a parent and pretend the parent has no notification at all" 不是一回事。

延迟加载意味着仅当代码从列表中读取通知时才加载通知,例如使用调试器打印它们时,或将它们序列化为 JSON 时,或获取列表。

如果你真的想测试延迟加载是否正常工作,那么加载父级,结束事务并关闭实体管理器,并检查获取列表的大小是否会抛出异常。或者加载父级,然后分离它,然后检查获取列表的大小是否会引发异常。或者加载父级,并检查 Hibernate.isInitialized(parent.getNotifications()) 是否为假。