Spring数据Hibernate JPQL聚合查询
我有一个带有实体的Spring数据实现Spring数据Hibernate JPQL聚合查询,hibernate,spring-data,Hibernate,Spring Data,我有一个带有实体的Spring数据实现 @Entity public class Account extends AbstractEntity { ... @OneToMany(mappedBy = "account") private Set<AccountTransaction> accountTransactions; 以及我的存储库,在这里我试图执行一个聚合查询:sum(amount) 但是,结果是null public interface Accoun
@Entity
public class Account extends AbstractEntity {
...
@OneToMany(mappedBy = "account")
private Set<AccountTransaction> accountTransactions;
以及我的存储库,在这里我试图执行一个聚合查询: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);
}
这显然是不可取的。。。因为我不想为每个查询都写这个 必须添加一个
JoinColumn
来建立关系:
@ManyToOne(optional = false)
@JoinColumn(name="FOREIGN_KEY_HERE")
@JsonIgnore
private Account account;
我没有看到任何
JoinColumn
注释来定义Account
和AccountTransaction
之间的关系您的数据库列是否使用了适当的默认值?我认为@OneToMany(mappedBy=“Account”)
和@ManyToOne(可选=false)
options负责建立关联。。。到目前为止,其他所有内容都已正常加载…AccountTransaction中的外键名称是什么?这取决于名称是否使用了适当的defaults@KevinBowersox在数据库中创建后,它应该是account\u id
,它只是实体注释类中的帐户,因此在hbm2ddl
语句中,我看到休眠:alter table Account\u transactions add constraint FK\u lpcrni2dw78hajvb0gfd5xcr外键(Account\u transactions)引用Account
,这是一个随机生成的FK约束。我按照我为AccountTransaction
实体设置的命名约定添加了@JoinColumn(name=“AccountTransactions”)
,但它仍然返回null。还想知道使用改进的命名策略(在我启动Spring Boot
时默认)是如何影响这一点的account\u id
是在AccountTransaction
上创建的列,而mappedBy
默认会看到该列:(关于JoinColumn
,说明它已经有了一个?)将工作的join column\u id命名为account\u感谢@KevinbowerBox。。。资本化@乔丹,鲍克,很高兴我能帮上忙!
@Query(value = "SELECT sum(amount) FROM account_transaction WHERE account_id = :accountId", nativeQuery = true)
public BigDecimal getAccountBalance(@Param("accountId") Long accountId);
@ManyToOne(optional = false)
@JoinColumn(name="FOREIGN_KEY_HERE")
@JsonIgnore
private Account account;