Spring OneToMany 的数据投影 returns 结果太多

Spring Data Projection with OneToMany returns too many results

我有一个具有单对多关系 (ContactInfo) 的 JPA 实体 (Person)。

@Entity
public class Person {
    @Id
    @GeneratedValue
    private Integer id;
    private String name;
    private String lastname;
    private String sshKey;
    @OneToMany(mappedBy = "personId")
    private List<ContactInfo> contactInfoList;
}

@Entity
public class ContactInfo {
    @Id
    @GeneratedValue
    private Integer id;
    private Integer personId;
    private String description;
}

我已经定义了一个投影接口,其中包含 here 所述的这种单对多关系。

public interface PersonProjection {
    Integer getId();
    String getName();
    String getLastname();
    List<ContactInfo> getContactInfoList();
}

public interface PersonRepository extends JpaRepository<Person,Integer> {
    List<PersonProjection> findAllProjectedBy();
}

当我使用 findAllProjectedBy 检索数据时,结果包含太多行。看起来返回的数据是类似于以下内容的连接查询的结果:

select p.id, p.name, p.lastname, ci.id, ci.person_id, ci.description 
from person p 
join contact_info ci on ci.person_id = p.id

例如这个数据集:

insert into person (id,name,lastname,ssh_key) values (1,'John','Wayne','SSH:KEY');

insert into contact_info (id, person_id, description) values (1,1,'+1 123 123 123'), (2,1,'john.wayne@west.com');

findAllProjectedBy 方法 returns 2 个对象(不正确)和标准 findAll returns 1 个对象(正确)。

完整项目是here

我已经进行了一些调试,看来问题出在 jpa 查询上。 findAll 方法使用此查询:

select generatedAlias0 from Person as generatedAlias0

findAllProjectedBy 使用此查询:

select contactInfoList, generatedAlias0.id, generatedAlias0.name, generatedAlias0.lastname from Person as generatedAlias0 
left join generatedAlias0.contactInfoList as contactInfoList

有谁知道如何解决这种无效行为?

此处介绍了此问题的快速修复方法: https://jira.spring.io/browse/DATAJPA-1173

您需要使用@Value 注释来描述单个投影属性之一。对于上面发布的示例,您将得到:

import java.util.List;
import org.springframework.beans.factory.annotation.Value;

public interface PersonProjection {
    @Value("#{target.id}")
    Integer getId();
    String getName();
    String getLastname();
    List<ContactInfo> getContactInfoList();
}