我有两个与父/子一对多关系的课程:
父:
@Entity
@Table(name="RMS.COMMITMENT_REGISTER")
public class CommitmentRegister {
@Id
@Column(name="COMMIT_REG_ID")
private int id;
@OneToMany(fetch=FetchType.EAGER)
@JoinColumn(name="COMMIT_REG_ID")
private List<CommitmentRegisterDetail> details;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<CommitmentRegisterDetail> getDetails() {
return details;
}
public void setDetails(List<CommitmentRegisterDetail> details) {
this.details = details;
}
}
和孩子:
@Entity
@Table(name="RMS.COMMITMENT_REGISTER_DETAIL")
public class CommitmentRegisterDetail {
@Id
@Column(name="COMMIT_REG_DETAIL_ID")
private int id;
@Column(name="AMOUNT")
private BigDecimal amount;
@ManyToOne(fetch=FetchType.EAGER)
@JoinColumn(name="COMMIT_REG_ID")
private CommitmentRegister commitmentRegister;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
public CommitmentRegister getCommitmentRegister() {
return commitmentRegister;
}
public void setCommitmentRegister(CommitmentRegister parent) {
this.commitmentRegister = parent;
}
}
我想查询其详细信息总和超过100的CR。我正在使用以下查询:
StringBuffer sql = new StringBuffer();
sql.append( " SELECT CR " );
sql.append( " FROM CommitmentRegister CR " );
sql.append( " LEFT JOIN CommitmentRegisterDetail CRD ON ( CRD.commitmentRegister = CR ) ");
sql.append( " WHERE CR.id >= 91000 " );
sql.append( " GROUP BY CR " );
sql.append( " HAVING SUM( CRD.amount ) > 100 " );
Query q = em.createQuery( sql.toString() );
return q.getResultList();
但是我收到以下错误:
Local Exception Stack:
Exception [EclipseLink-6015] (Eclipse Persistence Services - 2.4.1.v20121003-ad44345): org.eclipse.persistence.exceptions.QueryException
Exception Description: Invalid query key [amount] in expression.
Query: ReportQuery(referenceClass=CommitmentRegister jpql=" SELECT CR FROM CommitmentRegister CR LEFT JOIN CommitmentRegisterDetail CRD ON ( CRD.commitmentRegister = CR ) WHERE CR.id >= 91000 GROUP BY CR HAVING SUM( CRD.amount ) > 100 ")
查询在没有HAVING行的情况下运行正常,并且正确的详细信息被分配给父级(CR)。
提前致谢。
表格结构,如果相关
COMMITMENT_REGISTER
COMMIT_REG_ID
COMMITMENT_REGISTER_DETAIL
COMMIT_REG_DETAIL_ID
COMMIT_REG_ID
AMOUNT
答案 0 :(得分:0)
我的猜测是,除了HAVING
之外,它必须在联接方面做得更多,因为HAVING
应该按EclipseLink docs工作。
也许尝试这样的事情,看看它是怎么回事:
StringBuffer sql = new StringBuffer();
sql.append( " SELECT CR " );
sql.append( " FROM CommitmentRegisterDetail CRD " );
sql.append( " LEFT JOIN CRD.commitmentRegister CR ");
sql.append( " WHERE CR.id >= 91000 " );
sql.append( " GROUP BY CRD.commitmentRegister " );
sql.append( " HAVING SUM( CRD.amount ) > 100 " );
Query q = em.createQuery( sql.toString() );
return q.getResultList();