需要使用JPA @Query

时间:2018-11-02 07:27:25

标签: java mysql spring spring-boot jpql

我有一个自定义对象

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

我需要使用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);

}

这是我的Controller方法:

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

我的数据库名称很好。当我要求其他方法时,它可以完美工作。 请给我建议一个理想的解决方案。

3 个答案:

答案 0 :(得分:0)

1),您需要为SaleReport类创建一个构造函数,该构造函数接受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(更改的联接)。

答案 1 :(得分:0)

Spring有一个名为@SqlResultSetMapping的注释 此注释可以用于上述问题。可以从以下链接找到有关此批注的详细信息:

Annotation Type ConstructorResult

这实际上是将休眠查询结果映射到普通的POJO类中。那就是实际需要的东西。

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与您的POJOdatatype相同。

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

答案 2 :(得分:0)

我希望这个答案对您有帮助!

销售是您的实体类,而 SaleReport是pojo 类。

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

您不能从数据库返回pojo类列表,而是返回实体类列表。 使用公共列表而不是公共列表

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

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

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

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

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

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列表。