A Reader entity has a one-to-many,bidirectional relationship with a
Book entity. Two Reader entities are persisted,each having two Book
entities associated with them. For example,reader 1 has book a and
book b,while reader 2 has book c and book d. Which query returns a
Collection of fewer than four elements?
A. SELECT b.reader FROM Book b
B. SELECT r FROM Book b INNER JOIN b.reader r
C. SELECT r FROM Reader r INNER JOIN r.books b
D. SELECT r from Book b LEFT JOIN b.reader r LEFT JOIN FETCH r.books
鉴于答案是C,我认为这是不正确的.据我所知,JPA提供者将生成两个表的内连接的sql.因此,在所有情况下,我们将获得4条记录.我已经进行了一对多关系的测试,并且包含了重复项.
谁错了,我还是太阳?
解决方法
规范中有两个与重复相关的陈述.
> JOIN FETCH是JOIN的变体,但它确实表明类似的JOIN语义适用(除了选择了更多数据).规范(JPA v2.0的4.4.5.3节)给出了一个返回重复Department行的示例,尽管Employee对象不在select子句中.
>更直接的引用是在SELECT部分(JPA v2.0的4.8节)中,它清楚地说明了这一点
“如果未指定DISTINCT,则不会消除重复值.”
事实上,许多JPA提供商确实删除了重复项,原因如下:
a)用户的便利性,因为一些用户在sql中不够了解并且不期望它们b)通常不存在需要重复的用例c)可以将它们添加到结果集中,如果维护了对象标识,则会自动消除重复