如何使用 3 个 ManyToOne 组件进行查询?

How to make a query with 3 ManyToOne components?

我得到了一个带有 table 结果的数据库,它看起来像这样:

Table 结果:

resultId, resultValue, patientId (its a Foreign key of the table Patient), scriptId(Foreign key of ScriptMW), userId(Foreign key of User)

我忘记了 table 用户也有一个外键,来自 patientId 所以 1 个用户有更多的病人....它的 OneToMany 注释在那里 都是整数

这就是它的样子,在我的 java 代码中我得到了这个:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer resultId;

@ManyToOne
private User user;

@ManyToOne
private ScriptMW scriptMW;

@ManyToOne
private Patient patient;

@Lob
@Column(length=65536)
private String resultValue;

所以你可以看到它是 ManyToOne 注释的 3 倍

现在我需要进行查询以获取一名患者的所有结果,该患者属于使用了特定脚本的用户...

我得到了 userId、ScriptId 和 patientId 作为路径参数,这有效....但现在我需要获取所有值...但我不知道该怎么做...看下面的代码

我什至select结果

@Override
public List<Result> getResults(Integer userId, Integer scriptId, Integer patientId) {

    Query q=em.createQuery("Select r From Result r");
    return q.getResultList();

}

我执行之前的代码后出现此错误:

Caused by: com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: entities.User.patients, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->entities.Result["user"]->entities.User["patients"])

有什么想法吗?

我找到了答案,问题出在用户身上

@OneToMany(cascade={CascadeType.ALL})
private Set<Patient> patients;

他很懒惰(默认),但必须很热心

@OneToMany(fetch = FetchType.EAGER, cascade={CascadeType.ALL})
private Set<Patient> patients;

添加后,我使用了以下查询,它全部有效...

Query q=em.createQuery("Select r From Result r where r.user.userId=:userId and r.scriptMW.scriptId=:scriptId and r.patient.patientId=:patientId")
            .setParameter("userId", userId).setParameter("scriptId", scriptId).setParameter("patientId", patientId);

这是我问题的答案,但我仍然不喜欢它必须是 EAGER,有没有更好的方法?