简体   繁体   English

如何在Spring Boot中使存储库findBy()具有多个字段?

[英]How to make repository findBy() with more than one field in Spring Boot?

I want to make restcontroller findbyProductIdandYear in Spring Boot java aplication, but I get error, How to make it in great way? 我想在Spring Boot Java应用程序中使restcontroller findbyProductIdandYear,但出现错误,如何以一种很好的方式实现它?

Here is my model: 这是我的模型:

   @Entity
   @Table(name="view_disbursement_by_project")
   public class ViewDisbursement {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id")
private int id;

@Column(name="project_id")
private String projectId;

@Column(name="stage")
private String stage;

@Column(name="no")
private Integer no;

@Column(name="months")
private Integer months;

@Column(name="years")
private Integer years;

@Column(name="count")
private Integer count;

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getProject_id() {
    return projectId;
}

public void setProject_id(String project_id) {
    this.projectId = project_id;
}

public String getStage() {
    return stage;
}

public void setStage(String stage) {
    this.stage = stage;
}

public Integer getNo() {
    return no;
}

public void setNo(Integer no) {
    this.no = no;
}

public String getProjectId() {
    return projectId;
}

public void setProjectId(String projectId) {
    this.projectId = projectId;
}

public Integer getMonths() {
    return months;
}

public void setMonths(Integer months) {
    this.months = months;
}

public Integer getYears() {
    return years;
}

public void setYears(Integer years) {
    this.years = years;
}

public Integer getCount() {
    return count;
}

public void setCount(Integer count) {
    this.count = count;
}

    }

Here is my repository: 这是我的存储库:

    @Repository
    public interface ViewDisbursementRepository extends 
    JpaRepository<ViewDisbursement, Integer> {

List<ViewDisbursement> findByProjectIdandYear(String projectId, 
    Integer years);

    }

Here is my service: 这是我的服务:

    @Service
    public class ViewDisbursementService {

@Autowired
ViewDisbursementRepository vdr;

 public ArrayList<ViewDisbursement> getAll(){
       ArrayList<ViewDisbursement> list = new 
           ArrayList<ViewDisbursement>();
       vdr.findAll().forEach(list::add);
       return list;
    }

 public List<ViewDisbursement> getProjectDisbursement(String id, Integer year){
     return vdr.findByProjectIdandYear(id, year);
 }

And here is my controller: 这是我的控制器:

      @RestController
      @RequestMapping(path = "/dashboard")
      public class ViewDisbursementController {
     private static final Logger l = 
      LoggerFactory.getLogger(ViewDisbursementController.class);

  @Autowired
  ViewDisbursementService vds;

      @GetMapping(path = "/disbursement/{id}/{year}")

      public HighchartData getDisbursement(@PathVariable String id, Integer year)
{
      l.info("getting id : " + id);

      List<ViewDisbursement> lvd = vds.getProjectDisbursement(id, year);

      l.info(lvd.size() + "");

      List<ViewDisbursement> lvdActual = new ArrayList<ViewDisbursement>();
      List<ViewDisbursement> lvdPlan = new ArrayList<ViewDisbursement>();


    // Dipilah berdasarkan stage
    for (ViewDisbursement d : lvd) {
        if (d.getStage().equals("ACTUAL")) 
            lvdActual.add(d);
        else
            lvdPlan.add(d); 
    }

    // Total Plan
    Integer totalPlan = 0;
    for (ViewDisbursement d : lvdPlan) {
        totalPlan += d.getCount();
    }
    l.info("Total " + totalPlan);

    // Plan
    List<Double> plan = new ArrayList<Double>();
    double currentPlan = 0;
    //Iterasi berdasarkan bulan
    for (int i = 1; i <= 12; i++) {
        Integer count = getCount(lvdPlan, i);
        double current = ( count / (double) totalPlan) * 100;
        plan.add( current + currentPlan);
        currentPlan +=  current;
    }
    for (Double d : plan) {
        l.info("Nilai Plan " + d);
    }

    // Actual
    List<Double> actual = new ArrayList<Double>();
    double currentActual = 0;
    //Iterasi berdasarkan bulan
    for (int i = 1; i <= 12; i++) {
        Integer count = getCount(lvdActual, i);
        double current = ( count / (double) totalPlan) * 100;
        actual.add( current + currentActual);
        currentActual +=    current;
    }
    for (Double d : actual) {
        l.info("Nilai Actual " + d);
    }


    // Nilainya sudah lengkap
    // Masukkan ke Highchart

    HighchartData result = new HighchartData();
    ChartData chart = new ChartData("line");
    TitleData title = new TitleData("Disbursement");
    AxisData xAxis = new AxisData();
    xAxis.setCategories(new String[] {
            "JAN", "FEB", "MAR",
            "APR", "MEI", "JUN",
            "JUL", "AUG", "SEP",
            "OKT", "NOV", "DES"});


    SeriesData series = new SeriesData();
    series.setName("PLAN");
    series.setData(plan.toArray(new Double[plan.size()]));

    SeriesData series2 = new SeriesData();
    series2.setName("ACTUAL");
    series2.setData(actual.toArray(new Double[actual.size()]));

    result.setChart(chart);
    result.setTitle(title);
    result.setxAxis(xAxis);
    result.setSeries(new SeriesData[] {series, series2});

    return result;
    }

     private Integer getCount(List<ViewDisbursement> lvd, Integer month) {
    for (ViewDisbursement d : lvd) {
        if(d.getMonths() == month)
            return d.getCount();
    }
    return 0;
    }
    }

After running the program I get this error: 运行程序后,出现此错误:

    Error starting ApplicationContext. To display the conditions report 
    re-run your application with 'debug' enabled.
    2019-08-01 11:52:44.573 ERROR 9408 --- [           main] 
    o.s.boot.SpringApplication               : Application run failed

    org.springframework.beans.factory.UnsatisfiedDependencyException: 
    Error creating bean with name 'viewDisbursementController': 
    Unsatisfied dependency expressed through field 'vds'; nested exception 
    is org.springframework.beans.factory.UnsatisfiedDependencyException: 
    Error creating bean with name 'viewDisbursementService': Unsatisfied 
    dependency expressed through field 'vdr'; nested exception is 
    org.springframework.beans.factory.BeanCreationException: Error 
    creating bean with name 'viewDisbursementRepository': Invocation of 
    init method failed; nested exception is 
    java.lang.IllegalArgumentException: Failed to create query for method 
    public abstract java.util.Listcom.fusi24.pmorest.repository.ViewDisbursementRepository.findByP 
    rojectIdandYear(java.lang.String,java.lang.Integer)! No property 
    projectIdandYear found for type ViewDisbursement!

Use 采用

findByProductIdAndYears(String projectId, Integer years)
  • While using findBy for more than one parameter conjunction should be done using And, We have to keep A instead of a. 使用findBy进行多个参数连接时,应使用And进行,我们必须保留A而不是a。
  • We have to use the name as per define in Entity (for here we have Year which should be Years) 我们必须使用实体中定义的名称(为此,我们有Year应该是Years)

For Example 例如

@Entity
private String productId;

findById(String id) //wiil not work
findByProductId(String id) //work

 @Repository
    public interface ViewDisbursementRepository extends JpaRepository<ViewDisbursement, Integer> {

    List<ViewDisbursement> findByProjectIdAndYears(String projectId, Integer years);

    }

Apart from And/Or 除了And / Or

Derived queries with the predicates IsStartingWith, StartingWith, StartsWith, IsEndingWith", EndingWith, EndsWith, IsNotContaining, NotContaining, NotContains, IsContaining, Containing, Contains the respective arguments for these queries will get sanitized. 谓词为IsStartingWith,StartingWith,StartsWith,IsEndingWith”,EndingWith,EndsWith,IsNotContaining,NotContaining,NotContains,IsContaining,Containing的派生查询将包含这些查询的各自参数。

JPA Query JPA查询

Your field name is: 您的字段名称是:

@Column(name="years")
private Integer years;

You have appropriate getters and setters for the same. 您具有相同的适当的获取器和设置器。

And you are using a query method in repository as: 并且您在存储库中使用查询方法如下:

List<ViewDisbursement> findByProjectIdandYear(String projectId, Integer years);

It should be findByProjectIdAndYears an 's' in the end. 最后应该是findByProjectIdAndYears一个“ s”。 Then only it will match the field name. 然后只有它会匹配字段名称。 Also there is 'and' instead of 'And'. 还有“和”而不是“和”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM