1

I cannot find similar question, so I post this question. I'm pleased to be linked similar question I have.

My Spring server get some parts of 3 Data from UI client and will give appropriate data to UI client found in DB. I have to identify and execute respectively findby~ function for it.

In 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
}

Is there any simple way to do this??


extra

In Project

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

In ProjectDto

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

    private String yearCodeName;

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

    private String seasonCodeName;
    ... other properties
}
enjoey
  • 59
  • 1
  • 5

1 Answers1

0

You don't have to use findBy... method for each case. Spring Data has special Specification interface to define reusable predicate. Just implement toPredicate(..) method from this interface and use your implementation as a parameter in repository method:

List<Project> findAll(Specification spec);

See more:

Spring Data Specifications and Querydsl

REST Query Language with Spring Data JPA Specifications

Ruslan
  • 6,090
  • 1
  • 21
  • 36