对延迟加载感到困惑 [英] confused about Lazy loading

查看:69
本文介绍了对延迟加载感到困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试对延迟加载进行一些测试时,为了检查我是否理解得很好,我完全感到困惑。

While trying to do some tests on lazy loading, to check if i'm understanding it well, i got totally confused.

这里是我正在使用的实体在我的测试中:

Here's the entities i'm using on my test:

@Entity
public class Family {
@Id
private int id;


@OneToMany(mappedBy="family", fetch=FetchType.LAZY)
private Set<Person> members;

//getters & setters

public String toString(){
    String s="";
    for(Person p:getMembers()){
        s+=p.getFirstName();
    }
    return s;
}
}

@Entity
public class Person implements Comparable<Person>{
@Id
private int id;

private String firstName;
private String lastName;

@ManyToOne
private Family family;

//getters &setters
}

这是我的主要方法:

public static void main(String[] args) {
    factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    em = factory.createEntityManager();

    Query q = em.createQuery("select f from Family f");
    List<Family> families= q.getResultList();

    em.clear();
    em.close();
    factory.close();

    for(Family f:families){
        System.out.println(f);
    }
}


我从延迟加载中了解到,就是说,如果某个属性被标记为延迟获取,并且在管理时无法访问,则该属性将不会加载到内存中,并且以后对其进行任何尝试都将无法进行。现在令我困惑的是,即使通过关闭EM和EMF,通过分离的Family列表访问惰性成员属性时,上述测试也没有任何问题! ……正常吗?我是不是很了解懒加载概念?

What i understood from lazy loading, is that if an attribute is marked to be fetched lazily, and doesn't get accessed while it's managed, it won't be loaded in memory and any attempt to access it later won't work. Now what confuses me is that the test described above doesn't have any problem when accessing the lazy members attribute through the detached Family list, even after closing the EM and the EMF ! ... Is that normal? Am-i miss-understanding the lazy loading concept?

注意:我正在使用带有嵌入式DB的J2SE环境。我的提供者是EclipseLink

Note : I'm using a J2SE environment with an embedded DB. My provider is EclipseLink

感谢前进

George

Thanks in Advance
George

推荐答案

检查关闭工厂之前未触发toString方法,例如是否正在记录实体。我不建议在toString方法中触发关系,因为这容易出错,并且可能会意外触发。假设这不是问题的一部分,那么打开EclipseLink日志记录将帮助您显示在工厂生命周期中何处可以访问它。

Check that your toString method is not triggered before the factory is closed, such as if the entity is being logged. I would not recommend triggering relationship in a toString method as this is error prone and can be triggered unexpectedly. Turning on EclipseLink logging will help show you where it gets accessed in the factory's lifecycle, assuming it is not part of the problem.

这篇关于对延迟加载感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆