【问题标题】:JPA how to query the database without creating a tableJPA如何在不创建表的情况下查询数据库
【发布时间】:2014-07-28 06:33:57
【问题描述】:

我正在为我的数据库任务使用 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,但它不带参数

【问题讨论】:

    标签: java hibernate jpa annotations


    【解决方案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")
      

    @参见JSR-000220 Enterprise JavaBeans 3.0 Final Release (persistence)中的第 4.8.2 章“SELECT 子句中的构造函数表达式”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-11
      • 1970-01-01
      • 2021-08-04
      • 1970-01-01
      • 1970-01-01
      • 2019-07-24
      相关资源
      最近更新 更多