JPA如何在不创建表的情况下查询数据库

时间:2014-07-28 06:33:57

标签: java hibernate jpa annotations

我正在使用JPA和Spring来完成我的数据库任务,我需要在JPA Repo类中有如下所示的连接查询

@Query("SELECT 1 as id, COUNT(bill) as bills, ba.resource, MAX(b.updatedAt) as latestdate FROM Bill b join b.billComp ba where ba.comp.comp = ?1  group by ba.resource")
public List<BillCalc> findByBills(Long comp);

我的实体类如下

@Entity
public class BillCalc {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;

@Column(name = "latestdate", nullable = false)
private Date latestdate;

@Column(name = "bills", nullable = false)
private Long bills;

@Column(name = "resource", nullable = false)
private String resource;

我无法为此创建表格,有人可以帮助我使映射工作吗?它给出了一个错误,说不能从Object转换为BillCalc。

我尝试了@SubSelect,但没有参数

1 个答案:

答案 0 :(得分:1)

  1. 将构造函数添加到BillCalc

    BillCalc(Integer id, long bills, String resouce, Date latestdate) {...}
    
  2. 然后使用Select new查询:

    SELECT new BillCalc(1, COUNT(bill), ba.resource, MAX(b.updatedAt)) 
        FROM Bill b join b.billComp ba
        WHERE ba.comp.comp = ?1  group by ba.resource")
    
  3. @参见JSR-000220 Enterprise JavaBeans 3.0 Final Release (persistence)

    中的章节4.8.2“SELECT子句中的构造函数表达式”