将SQL查询转换为Hibernate

时间:2018-07-27 13:21:53

标签: sql hibernate hql

我一直在尝试从表中获取统计信息。 here介绍了有关我的表结构和目标的全部详细信息。

我在将SQL查询转换为HQL时遇到问题。

这是我的本机SQL查询:

 SELECT  td.profile_id, 
  sum(td.amount) AS summa_deposit, 
  (
   SELECT sum(tw.amount) AS summa_withdraw
     FROM public.main_transaction AS tw 
     WHERE tw.profile_id=td.profile_id
            AND tw.pub_date>='2017-01-01' 
            AND tw.pub_date<='2017-03-21' 
            AND tw.transaction_type IN ('WITHDRAW','WITHDRAW_MANUAL')
  ),
  (
  SELECT SUM(b.amount) AS summa_bonus
     FROM public.bonus b JOIN
          public.main_transaction tw 
          ON b.transaction_id = tw.id
     WHERE tw.profile_id = td.profile_id 
            AND tw.pub_date >= '2017-01-01' 
            AND tw.pub_date <= '2017-03-21'
  )
FROM public.main_transaction AS td
WHERE td.pub_date>='2017-01-01' 
      AND td.pub_date<='2017-03-21' 
      AND td.transaction_type IN ('DEPOSIT','DEPOSIT_MANUAL') 
GROUP BY  td.profile_id
ORDER BY td.profile_id;

这是我的HQL查询,用作名为 StatisticsMonthlyBalanceDTO

的结果类(构造函数表达式)
 @Query("SELECT new com.xxx.xxxx.service.dto.StatisticsMonthlyBalanceDTO( td.profile.id, SUM(td.amount), (" +
        "   SELECT SUM(tw.amount) " +
        "       FROM Transaction tw " +
        "       WHERE " +
        "       tw.transactionType IN ('WITHDRAW','WITHDRAW_MANUAL') " +
        "       AND tw = td " +
        "       AND tw.pubDate >= :fromDate " +
        "       AND tw.pubDate <= :toDate " +
        "), (" +
        "  SELECT SUM (m.amount) " +
        "       FROM Transaction tmp " +
        "       LEFT JOIN Bonus b ON b.transaction.id = tmp.id " +
        "       WHERE tmp.profile.id = td.profile.id " +
        "       AND tmp.pubDate >= :fromDate " +
        "       AND tmp.pubDate <= :toDate " +
        "))" +
        " FROM Transaction td " +
        " WHERE td.transactionType IN ('DEPOSIT','DEPOSIT_MANUAL') " +
        " AND td.pubDate >= :fromDate " +
        " AND td.pubDate <= :toDate " +
        " GROUP BY td.profile")

StatisticsMonthlyBalanceDTO 实体类如下。

public class StatisticsMonthlyBalanceDTO {

    private Long profileId;

    private String profilePhone;

    private BigDecimal totalDeposit;

    private BigDecimal totalWithdraw;

    private BigDecimal totalBonusPlus;

    private BigDecimal totalBonusMinus;

    private static final Logger log = LoggerFactory.getLogger(StatisticsMonthlyBalanceDTO.class);

    public StatisticsMonthlyBalanceDTO(Object profileId, Object profilePhone, Object totalDeposit, Object totalWithdraw, Object totalBonusPlus, Object totalBonusMinus) {
        this.profileId =  Long.valueOf((Long) profileId);
        this.profilePhone = (String) profilePhone;
        this.totalDeposit = (BigDecimal) totalDeposit;
        this.totalWithdraw = (BigDecimal) totalWithdraw;
        this.totalBonusPlus = (BigDecimal) totalBonusPlus;
        this.totalBonusMinus = (BigDecimal) totalBonusMinus;
    }...

0 个答案:

没有答案