java - 延迟加载不起作用 - 我只需要父对象,而不是所有关联

标签 java hibernate jpa hql lazy-loading

如何在没有所有子关联的情况下获得我想要的对象。

我有我的类(class)网站:

@Entity
@Table(name = "Sites")
public class Site {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "Id_Site", unique = true, nullable = false)
    private long Id_Site;
    private String ...;
    private boolean ...;
    private long ...; 
    private Date ...;
    private Date ...;
    private String ...;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Sequence> sequences = new HashSet<>();

    @ManyToOne
    private ... ...;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<...> ... = new HashSet<>();

    @ManyToOne
    private ... ...;

    public constructor...

    public set..
    public get..
}

我只需要一个站点对象,不需要序列关联。

在我的序列表中,我有:

@Entity
@Table(name = "Sequences")
public class Sequence {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "Id_Sequence", unique = true, nullable = false)
    private long Id_Sequence;
    private Date ....;
    private Date ....;
    private String ....;
    private String ....;
    private String ....;
    private int ....;
    private int ....;
    private double ....;
    private double ....;
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<TraceSequence> traceSequences = new HashSet<>();
    @ManyToOne(cascade = CascadeType.ALL)
    private Site site;

    public constructor...

    public set..
    public get..
}

当我使用 FetchType.Lazy 并调用我的方法时:

@Override
public Site findSiteByName(String Name_Site) {
    List<Site> sites = entityManager.createQuery("SELECT s FROM Site s").getResultList();
    for (Site item : sites) {
        if (item.getNom_Site().equals(Name_Site)) {
            return item;
        }
    }
    return null;
}

我收到这个错误:

failed to lazily initialize a collection of role: xxx.xxx.xxx.xxx.xxx.site.Site.sequences, could not initialize proxy - no Session

当我使用FetchType.EAGER时,我不仅获得了一个Site对象,而且还获得了所有序列对象,以及其他序列关联的所有对象。 (我知道这是正常的 react 。)

请知道为什么这种延迟初始化尝试不起作用的人告诉我如何解决这个问题。

最佳答案

当 jpa 在 session 关闭后尝试获取数据时,会发生这些惰性错误。

但是使用 eager 会影响所有包含该实体的查询。

尝试在查询中使用联合提取而不是急切。

关于java - 延迟加载不起作用 - 我只需要父对象,而不是所有关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43592272/

相关文章:

java - IBM Websphere JPA org.apache.openjpa.persistence.ArgumentException

java - 在java中更改javafx文件的路径

java - 保存子对象列表时出现 org.hibernate.NonUniqueObjectException

java - JPA 对象引用未保存的 transient 实例 - 在刷新之前保存 transient 实例

java - 单元测试 JPA 查询

java - 在 ConstraintValidator 中注入(inject) EntityManager

Java 和 Heritrix 3.1.x : Web Content parsing?

Java - 从包含该库的项目中获取信息到库项目中

java - 是否有任何选项可以在项目中构建单个 java 文件

java - 使用 HQL 进行条件更新