Spring Data Hibernate JPQL聚合查询

时间:2014-02-07 20:04:17

标签: hibernate spring-data

我有一个带有实体的Spring Data实现

@Entity
public class Account extends AbstractEntity {

...

    @OneToMany(mappedBy = "account")
    private Set<AccountTransaction> accountTransactions;

AccountTransactions

@Entity(name="AccountTransactions")
public class AccountTransaction extends AbstractEntity {

    /**
     * 
     */
    private static final long serialVersionUID = -7045838402463741959L;

    @ManyToOne(optional = false)
    @JsonIgnore
    private Account account;

    @Column
    @Enumerated(EnumType.ORDINAL)
    private TransactionType transactionType;

    @Column
    private BigDecimal amount;

我的存储库,我正在尝试执行聚合查询:sum(amount)

但结果是null

public interface AccountTransactionRepository extends
        CrudRepository<AccountTransaction, Long> {

    // @Query(value =
    // "select sum(amount) from AccountTransaction where account.id = ?1")
    @Query(value = "SELECT sum(at.amount) FROM AccountTransactions at WHERE at.account.id = :accountId")
    public BigDecimal getAccountBalance(@Param("accountId") Long accountId);
}

获取BigDecimal列的amount总和需要做些什么?

*的 更新 *

我能够让查询工作将其更改为nativeQuery,如下所示:

@Query(value = "SELECT sum(amount) FROM account_transaction WHERE account_id = :accountId", nativeQuery = true)
    public BigDecimal getAccountBalance(@Param("accountId") Long accountId);

这显然不太理想......因为我不想为每个查询都写这个......

1 个答案:

答案 0 :(得分:1)

您必须添加JoinColumn才能建立关系:

@ManyToOne(optional = false)
@JoinColumn(name="FOREIGN_KEY_HERE")
@JsonIgnore
private Account account;