【问题标题】:Hql clause is null in clause case , not working as in mysqlHql 子句在子句 case 中为空,不像在 mysql 中那样工作
【发布时间】:2014-09-02 13:23:49
【问题描述】:

我在mysql中做了一个查询。

SELECT COALESCE(SUM(t2.ammout * CASE WHEN t2.idAccountDeb = :accountSelec AND  
(t2.idAccountDeb <> t2.idAccountCred OR t2.idAccountCred IS NULL) 
THEN 1 WHEN t2.idAccountCred = :accountSelec AND
(t2.idAccountDeb <> t2.idAccountCred OR t2.idAccountDeb IS NULL) THEN
-1 ELSE 0 END),0) FROM TransactionAccount t2 WHERE 
(t2.idAccountDeb = :accountSelec OR t2.idAccountCred = :accountSelec) AND
t2.dtInf <= :dateSelec 

我尝试在 Hql 中转换

SELECT COALESCE(SUM(t2.ammout * CASE WHEN t2.accountDeb = :accountSelec AND 
(t2.accountDeb <> t2.accountCred OR t2.accountCred IS NULL) THEN 1
WHEN t2.accountCred = :accountSelec AND (t2.accountDeb <> t2.accountCred OR
t2.accountDeb IS NULL) THEN -1 ELSE 0 END),0) FROM TransactionAccount t2 
WHERE   (t2.accountDeb = :accountSelec OR t2.accountCred = :accountSelec) 
AND t2.dtInf <= :dateSelec 

但是在 hql 中返回 0.00,这个 END),0) 。在 mysql 中,150.97。

当帐户借方或帐户贷方为空时,会发生这种情况。

我做错了什么? 例子: 如果交易中有一个账户贷方或借方账户值为空,则查询不能在“为空”子句中捕获。

我的豆子:

    @Entity
    public class Account implements Serializable {
    @Id
    @GeneratedValue
    private long id;
    @Column(length = 40)
    private String cod;
    private boolean credit;
    private String name;//CTA
    @OneToOne
    @JoinColumn(name = "idCompany")
    private Company company;


    @Version
    private int version;

    //getter and setters
}

    @Entity
    public class Transaction implements Serializable {
    @Id
    @GeneratedValue
    private long id;
    private String history;
    @JoinColumn(name = "idAccountDeb")
    @OneToOne
    private Account accountDeb;
    @JoinColumn(name = "idAccountCred")
    @OneToOne
    private Account accountCred;
    private BigDecimal ammount;
    @Temporal(TemporalType.DATE)
    private Date dtInf;
    @Temporal(TemporalType.TIMESTAMP)
    private Date dtPosted;
    @Temporal(TemporalType.TIMESTAMP)
    private Date dtModif;  
    private TypeTransaction type;
    @Version
    private int version;
}

【问题讨论】:

  • 我不确定,但我不认为(例如)THEN -1 ELSE 0 END 是有效的 HQL(但当然,我可能是错的......)
  • 如果交易中有一个账户贷方或借方账户值为空,则查询不能在“为空”子句中捕获。

标签: java mysql hql


【解决方案1】:

我的解决方案。

只需将 id 放在比较帐户中

新查询:

SELECT COALESCE(SUM(t2.ammount * CASE WHEN t2.accountDeb.id = :accountSelec 
           AND (t2.accountDeb.id <> t2.accountCred.id OR t2.accountCred.id is null) THEN 1
           WHEN  (t2.accountDeb.id <> t2.accountCred.id 
           OR t2.accountDeb.id is null) THEN -1 ELSE 0 END),0)
           FROM TransactionAccount t2 WHERE (t2.accountDeb = :accountSelec 
           OR t2.accountCred = :accountSelec) AND t2.dtInf <= :dateSelec

【讨论】:

    猜你喜欢
    • 2014-07-14
    • 2018-06-17
    • 1970-01-01
    • 2010-12-02
    • 2016-03-24
    • 2016-03-02
    • 1970-01-01
    • 2017-05-02
    • 1970-01-01
    相关资源
    最近更新 更多