I have a Spring Data implementation with an entity
@Entity
public class Account extends AbstractEntity {
...
@OneToMany(mappedBy = "account")
private Set<AccountTransaction> accountTransactions;
And the 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;
And my repository, where I'm trying to execute an aggregate query: sum(amount)
The result is null however
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);
}
What do I need to do to get the BigDecimal sum of the column amount?
*UPDATE*
I was able to get the query to work changing it to a nativeQuery like so:
@Query(value = "SELECT sum(amount) FROM account_transaction WHERE account_id = :accountId", nativeQuery = true)
public BigDecimal getAccountBalance(@Param("accountId") Long accountId);
This is obviously less than desirable ... as I don't want to have to write this for every query ...
JoinColumnannotations to define the relationship betweenAccountandAccountTransactionare your database columns using the appropriate defaults?@OneToMany(mappedBy = "account")and@ManyToOne(optional = false)options took care of making the association ... so far everything else has loaded normally...AccountTransaction? It depends if the name uses the appropriate defaultsaccount_idafter it's been created in the database, and it's justAccountin the@Entityannotated class...