gpt4 book ai didi

java - 带有 OneToMany 的 Spring Data Projection 返回太多结果

转载 作者:搜寻专家 更新时间:2023-11-01 02:37:08 25 4
gpt4 key购买 nike

我有一个 JPA 实体(人),它具有一对多关系 (ContactInfo)。

@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;
}

我已经定义了一个投影接口(interface),其中包括描述的这种单对多关系 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 方法返回 2 个对象(错误),而标准的 findAll 方法返回 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();
}

关于java - 带有 OneToMany 的 Spring Data Projection 返回太多结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45987915/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com