需要 return 使用 JPA @Query 的自定义对象列表

Need to return List of Custom Object using JPA @Query

我有一个自定义对象

@Component
public class SaleReport {

    private Date date;
    private String customerName;
    private String phoneNo;
    private String productName;
    private Integer quantity;
    private Double totalAmount;

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getCustomerName() {
        return customerName;
    }

    public void setCustomerName(String customerName) {
        this.customerName = customerName;
    }

    public String getPhoneNo() {
        return phoneNo;
    }

    public void setPhoneNo(String phoneNo) {
        this.phoneNo = phoneNo;
    }

    public String getProductName() {
        return productName;
    }

    public void setProductName(String productName) {
        this.productName = productName;
    }

    public Integer getQuantity() {
        return quantity;
    }

    public void setQuantity(Integer quantity) {
        this.quantity = quantity;
    }

    public Double getTotalAmount() {
        return totalAmount;
    }

    public void setTotalAmount(Double totalAmount) {
        this.totalAmount = totalAmount;
    }
}

我需要 return 使用 JpaRepository<Sale, Integer> 这个对象的列表 SaleRepository如下:

@Repository
public interface SaleRepository extends JpaRepository<Sale, Integer> {


    @Query(value = "SELECT B.order_date AS date, E.customer_name AS customerName, " +
            "E.phone_no AS phoneNo, D.product_name AS productName, C.quantity AS quantity, " +
            "C.total_price AS totalAmount " +
            "FROM SALE A " +
            "INNER JOIN A.quotation_id B " +
            "INNER JOIN B.quotation_id C " +
            "INNER JOIN C.product_id D " +
            "INNER JOIN B.customer_id E " +
            "WHERE (B.order_date BETWEEN :from_date AND :to_date)", nativeQuery = true)
    public List<SaleReport> getSaleReportByDate(@Param("from_date")String fromDate, @Param("to_date")String toDate);

}

这是我的控制器方法:

@GetMapping("api/report/sale/{from_date}/{to_date}")
        public List<SaleReport> getSaleReportByDate(@PathVariable("from_date") String fromDate, @PathVariable("to_date") String toDate){
        return saleRepository.getSaleReportByDate(fromDate, toDate);
}

虽然我 运行 代码显示此错误:

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown database 'a'
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_161]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_161]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_161]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_161]
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:425) ~[mysql-connector-java-5.1.47.jar:5.1.47]
    at com.mysql.jdbc.Util.getInstance(Util.java:408) ~[mysql-connector-java-5.1.47.jar:5.1.47]
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:944) ~[mysql-connector-java-5.1.47.jar:5.1.47]

我的数据库名称没问题。当我用其他方法请求时,它工作得很好。 请给我一个理想的解决方案。

1) 您需要为 SaleReport class 创建一个构造函数,它接受您在 select 中使用的所有参数声明并按照确切的顺序。

2) 更改您的查询,以便用 new 语句包装所选列:

@Query(value = "SELECT new org.mypackage.SaleReport(B.order_date AS date,"
                        + "E.customer_name AS customerName, "
                        + "E.phone_no AS phoneNo, D.product_name AS productName, 
                        + "C.quantity AS quantity, " +
                        + "C.total_price AS totalAmount) " +
            "FROM SALE A " +
            "INNER JOIN A.quotation B " +
            "INNER JOIN B.quotation C " +
            "INNER JOIN C.product D " +
            "INNER JOIN B.customer E " +
            "WHERE (B.order_date BETWEEN :from_date AND :to_date)") 

3) 在我看来你不需要本地查询,你可以直接使用 HQL(更改连接)。

Spring 有一个名为 @SqlResultSetMapping 的注释 此注释可用于上述问题。有关此注释的详细信息,请参阅以下 link:

Annotation Type ConstructorResult

这实际上是将一个休眠查询结果映射到一个普通的 POJO Class。这才是真正需要的。

Example:

   Query q = em.createNativeQuery(
      "SELECT c.id, c.name, COUNT(o) as orderCount, AVG(o.price) AS avgOrder " +
      "FROM Customer c, Orders o " +
      "WHERE o.cid = c.id " +
      "GROUP BY c.id, c.name",
      "CustomerDetailsResult");

   @SqlResultSetMapping(
       name="CustomerDetailsResult",
       classes={
          @ConstructorResult(
               targetClass=com.acme.CustomerDetails.class,
                 columns={
                    @ColumnResult(name="id"),
                    @ColumnResult(name="name"),
                    @ColumnResult(name="orderCount"),
                    @ColumnResult(name="avgOrder", type=Double.class)
                    }
          )
       }
      )

@SqlResultSetMapping 放入任何 @Entity 的顶部并确保从数据库返回的 datatype 与您的 POJO Class datatype.

希望这对您有所帮助。享受 :)

希望这个回答对您有所帮助!!

Sale 是您的实体 class,SaleReport 是 pojo class。

public List<SaleReport> getSaleReportByDate(@Param("from_date")String fromDate, @Param("to_date")String toDate);

你不能 return 来自 database.It return 实体 class 列表的 pojo class 列表。 使用 public 列表而不是 public 列表

public List<Sale> getSaleReportByDate(@Param("from_date")String fromDate, @Param("to_date")String toDate);

@Repository
public interface SaleRepository extends JpaRepository<**Sale**, Integer>

您必须将实体 Class 列表映射到 POJO class 列表。

实体 class 列表到 pojo class 列表的映射: 因为有很多方法可以实现这一目标 最简单的解决方案是遍历实体 class 并将实体属性设置为 pojo 属性:

我不建议使用构造函数,因为有时您可能只想设置几个字段而不是 POJO 的所有字段 class。

Arraylist<SaleReport> sr = new Arraylist<SaleReport>();
ArrayList<Sale> saleEntityList= saleRepository.getSaleReportByDate(fromDate,toDate);
for(Sale  s : saleEntityList){
    saleReport = new SaleReport();
    saleReport.setDate(s.getDate);
    //same for all attributes
    sr.add(saleReport);
} 
return sr;

这里是你的 POJO 列表。