如何在 Spring Boot 中使存储库 findBy() 具有多个字段?
How to make repository findBy() with more than one field in Spring Boot?
我想在 Spring 启动 java 应用程序中创建 restcontroller findbyProductIdandYear,但出现错误,如何以更好的方式实现?
这是我的模型:
@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;
}
}
这是我的存储库:
@Repository
public interface ViewDisbursementRepository extends
JpaRepository<ViewDisbursement, Integer> {
List<ViewDisbursement> findByProjectIdandYear(String projectId,
Integer years);
}
这是我的服务:
@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);
}
这是我的控制器:
@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;
}
}
在 运行 程序之后我得到这个错误:
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!
使用
findByProductIdAndYears(String projectId, Integer years)
- 虽然将 findBy 用于多个参数连接应该使用 And,但我们必须保留 A 而不是 a。
- 我们必须使用实体中定义的名称 (这里我们有 Year,应该是 Years)
例如
@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);
}
除了And/Or
带有谓词 IsStartingWith、StartingWith、StartsWith、IsEndingWith"、EndingWith、EndsWith、IsNotContaining、NotContaining、NotContains、IsContaining、Containing、包含这些查询的相应参数的派生查询将被清理。
您的字段名称是:
@Column(name="years")
private Integer years;
您有相应的 getter 和 setter。
并且您在存储库中使用的查询方法为:
List<ViewDisbursement> findByProjectIdandYear(String projectId, Integer years);
最后应该是findByProjectIdAndYears
一个's'。然后只有它会匹配字段名称。还有 'and' 而不是 'And'.
我想在 Spring 启动 java 应用程序中创建 restcontroller findbyProductIdandYear,但出现错误,如何以更好的方式实现?
这是我的模型:
@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;
}
}
这是我的存储库:
@Repository
public interface ViewDisbursementRepository extends
JpaRepository<ViewDisbursement, Integer> {
List<ViewDisbursement> findByProjectIdandYear(String projectId,
Integer years);
}
这是我的服务:
@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);
}
这是我的控制器:
@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;
}
}
在 运行 程序之后我得到这个错误:
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!
使用
findByProductIdAndYears(String projectId, Integer years)
- 虽然将 findBy 用于多个参数连接应该使用 And,但我们必须保留 A 而不是 a。
- 我们必须使用实体中定义的名称 (这里我们有 Year,应该是 Years)
例如
@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);
}
除了And/Or
带有谓词 IsStartingWith、StartingWith、StartsWith、IsEndingWith"、EndingWith、EndsWith、IsNotContaining、NotContaining、NotContains、IsContaining、Containing、包含这些查询的相应参数的派生查询将被清理。
您的字段名称是:
@Column(name="years")
private Integer years;
您有相应的 getter 和 setter。
并且您在存储库中使用的查询方法为:
List<ViewDisbursement> findByProjectIdandYear(String projectId, Integer years);
最后应该是findByProjectIdAndYears
一个's'。然后只有它会匹配字段名称。还有 'and' 而不是 'And'.