如何执行 JOIN FETCH 查询以获得正确的结果?

How to preform the JOIN FETCH query to get the correct result?

好的伙计们,我得到了这样的东西:

一个学生的 ID、名字和姓氏...

现在我创建了一个名为 ACCOUNTS 的新 java class,其中包含 ID、名称和值

还有这个:

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

public Student() {
    accounts= new HashSet<BankAccout>();
}

    public Set<BankAccout> getAccounts() {
    return accounts;
}

public void setAccounts(Set<BankAccout> accounts) {
    this.accounts= accounts;
}

现在,我有了自己的网站,网站上有一个table所有学生的数据...他们都是独一无二的

然后我不得不写一个新的 class,我必须向我的网站添加一个列表框,它显示了选定的学生帐户...

我打电话给学生的旧查询如下所示:

@GET
@Path("/getAll")
@Produces(MediaType.APPLICATION_JSON)
public List<Student> getAll() {
    return em.createQuery("from Student s").getResultList();
}

控制器看起来像这样:

$http.get('http://localhost:8080/CreditCardWEB/rest/cc/getAll').success(
        function(data) {
            $scope.result = data;
        });

一切正常......在 table 中没有问题......但我必须更改查询才能将数据从帐户绑定到 table...现在查询看起来像这样...

return em.createQuery("from Student s inner join fetch s.accounts").getResultList();

现在,table 应该向我显示与以前相同的数据......也就是说,所有学生都是独一无二的......但它只向我展示那些至少有一个帐户....不仅如此,同一个学生在 table...

中显示的次数不止一次,而是多次(他的帐户数)

有什么建议吗?

INNER JOIN table 中过滤掉不匹配的记录。因此,您当前的加入正在删除没有帐户的学生。解决这个问题的方法是使用 LEFT JOIN,这将保留所有学生,即使他们没有帐户:

return em.createQuery("from Student s left join fetch s.accounts").getResultList();

我找到了解决方案,它与 Tim 的解决方案非常接近。

这里是:

    return em.createQuery("Select distinct s from Student s left join fetch s.accounts").getResultList();