Hibernate @Formula减法和加法

时间:2016-02-27 22:11:07

标签: java sql hibernate postgresql

我想使用Hibernate @Forumla注释来计算字段值:

balance = intialBalance +(sum(借记类型的交易) - (总和(CREDIT类型的交易))

我有桌面交易:

CREATE TABLE transaction
(
  idtransaction serial NOT NULL,
  directionoftransaction character varying NOT NULL,
  amount numeric,
  observation text,
  datetransaction timestamp without time zone,
  idtypeoftransaction bigint,
  idaccount bigint,
  iduser bigint,
  CONSTRAINT prk_constraint_transaction PRIMARY KEY (idtransaction),
  CONSTRAINT fk_transaction_idaccount FOREIGN KEY (idaccount)
      REFERENCES account (idaccount) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_transaction_idtypeoftransaction FOREIGN KEY (idtypeoftransaction)
      REFERENCES typeoftransaction (idtypeoftransaction) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT fk_transaction_iduser FOREIGN KEY (iduser)
      REFERENCES tuser (iduser) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT transaction_observation_key UNIQUE (observation)
)

她是帐户实体

@Entity
@Table(name = "account")
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "account_seq_gen")
    @SequenceGenerator(name = "account_seq_gen", sequenceName = "account_idaccount_seq", initialValue = 1, allocationSize = 1)
    @Column(name = "idaccount", unique = true, nullable = false)
    private Long idAccount;

    @Column(name = "namebank")
    private String nameBank;
    @Column(name = "accountnumber")
    private String accountNumber;
    @Column(name = "initialBalance")
    private BigDecimal intialBalance;
    @Formula("intialBalance + (select amount from Transaction t where directionoftransaction = 'CREDIT') minus (select amount from Transaction t where directionoftransaction = 'DEBIT')")
    private BigDecimal balance;


}

这给出了语法错误,那么我如何构造查询呢?

1 个答案:

答案 0 :(得分:0)

在更正查询语法后,我找到了解决方案。

@Entity
@Table(name = "account")
public class Account {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "account_seq_gen")
    @SequenceGenerator(name = "account_seq_gen", sequenceName = "account_idaccount_seq", initialValue = 1, allocationSize = 1)
    @Column(name = "idaccount", unique = true, nullable = false)
    private Long idAccount;

    @Column(name = "namebank")
    private String nameBank;
    @Column(name = "accountnumber")
    private String accountNumber;
    @Column(name = "initialBalance")
    private BigDecimal intialBalance;
    @Formula("COALESCE(initialSolde,0) + ((select COALESCE(sum(t.amount),0) from transaction t where t.idaccount = idAccount and t.directionoftransaction = 'CREDIT') - " +
            "(select COALESCE(sum(d.amount),0) from transaction d where d.idaccount = idAccount and d.directionoftransaction = 'DEBIT'))")
    private BigDecimal balance;


}