Dropwizard-Hibernate Lazy fetch不是懒惰的

时间:2017-09-15 03:56:30

标签: java postgresql hibernate dropwizard

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

父表:

@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(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获取,它总是会给我所有通知。是否应该懒散地提取通知?

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只是提示当属性为值时获取值   访问。除非你,否则Hibernate会忽略基本类型的此设置   正在使用字节码增强

1 个答案:

答案 0 :(得分:1)

&#34;懒洋洋地加载父母的通知&#34;和#34;不加载父母的通知并假装父母根本没有通知&#34;。

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

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

相关问题