gpt4 book ai didi

java - Spring Data Jpa Repository findBy 部分数据而不是通过执行所有情况

转载 作者:行者123 更新时间:2023-12-01 18:26:32 25 4
gpt4 key购买 nike

我找不到类似的问题,所以我发布这个问题。我很高兴能链接到我遇到的类似问题。

我的 Spring 服务器从 UI 客户端获取 3 个数据的某些部分,并将适当的数据提供给在数据库中找到的 UI 客户端。我必须分别识别并执行 findby~ 函数。

在 ProjectService 中

public List<Project> getProjectsByPartialData(ProjectDto projectDto) {
if (projectDto.getYearCodeName()!= null && projectDto.getCustomerCoName() != null && projectDto.getSeasonCodeName()!=null) {
return projectRepository.findByYearCodeNameAndCustomerCoNameAndSeasonCodeName(projectDto.getYearCodeName(),projectDto.getCustomerCoName(),projectDto.getSeasonCodeName());
} else if (projectDto.getYearCodeName() == null && projectDto.getCustomerCoName() != null && projectDto.getSeasonCodeName()!=null) {
return projectRepository.findByCustomerCoNameAndSeasonCodeName(projectDto.getCustomerCoName(),projectDto.getSeasonCodeName());
} else if (projectDto.getYearCodeName()!= null && projectDto.getCustomerCoName() == null && projectDto.getSeasonCodeName()!=null) {
return projectRepository.findByYearCodeNameAndSeasonCodeName(projectDto.getYearCodeName(),projectDto.getSeasonCodeName());
} else if (projectDto.getYearCodeName()!= null && projectDto.getCustomerCoName() != null && projectDto.getSeasonCodeName()==null) {
return projectRepository.findByYearCodeNameAndCustomerCoName(projectDto.getYearCodeName(),projectDto.getCustomerCoName());
} ...3 more to go
}

有什么简单的方法可以做到这一点吗?

<小时/>

额外

在项目中

@Entity
@Getter
@NoArgsConstructor
@ToString
@EqualsAndHashCode
public class Project {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;

@ManyToOne
@JoinColumn(name = "YEAR_CODE", referencedColumnName = "CODE")
private YearCode yearCode;

@ManyToOne
@JoinColumn(name = "CUSTOMER_CO_CODE", referencedColumnName = "CODE")
private CustomerCo customerCo;

@ManyToOne
@JoinColumn(name = "SEASON_CODE", referencedColumnName = "CODE")
private SeasonCode seasonCode;

... other properties
}

在 ProjectDto 中

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@ToString
public class ProjectDto {

private String yearCodeName;

@JsonProperty(value = "customerNameCode")
private String customerCoName;

private String seasonCodeName;
... other properties
}

最佳答案

您不必对每种情况都使用 findBy... 方法。 Spring Data 有特殊的Specification 接口(interface)来定义可重用的谓词。只需从此接口(interface)实现 toPredicate(..) 方法,并将您的实现用作存储库方法中的参数:

List<Project> findAll(Specification spec);

查看更多:

Spring Data Specifications and Querydsl

REST Query Language with Spring Data JPA Specifications

关于java - Spring Data Jpa Repository findBy 部分数据而不是通过执行所有情况,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60221626/

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