带有连接表的Hibernate HQL

时间:2012-08-27 00:35:58

标签: hibernate jpa annotations

此查询曾经起作用,不再适用。 (我正在切换到注释,这是剩下的两个破坏测试中的一个。)

我有三张桌子:

+---------------+
| Competition   | 
+---------------+
| competitionId | 
| . . .         | 
+---------------+

+---------------+
| Competitor    | 
+---------------+
| competitorId  | 
| . . .         | 
+---------------+

+------------------------+
| CompetitionCompetitors | 
+------------------------+
| competitionId          | 
| competitorId           | 
+------------------------+

以前的代码/查询是

Query query = session.createQuery(
    "select c.id from Competition c join c.competitors co where co.id = :competitorId" );
query.setParameter( "competitorId", competitor.getCompetitorId() );
List list = query.list();

以下是来自Hibernate的一些前面的SQL日志记录,以及错误消息:

Hibernate: update db.competition set competitorId=? where competitionId=?
Hibernate: update db.competition set competitorId=? where competitionId=?
Hibernate: update db.competition set competitorId=? where competitionId=?
17:12:49,232  WARN JDBCExceptionReporter:233 - SQL Error: 1054, SQLState: 42S22
17:12:49,240 ERROR JDBCExceptionReporter:234 - Unknown column 'competitorId' in 'field list'

(我承认,我很惊讶地看到查询发生了更新。)

以下是竞赛中的注释:

@OneToMany( targetEntity = Competition.class )
@JoinColumn( name = "competitorId" )
private Set< Competitor > competitors = new TreeSet< Competitor >();

我流了什么?

1 个答案:

答案 0 :(得分:1)

这可能是一个小的复制粘贴错误 - 你构造的查询是'查询'但是你执行的查询是'otherQuery'?

然而,我认为问题在于targetEntity值。来自规范:

  

作为关联目标的实体类。仅当使用Java泛型定义集合值关系属性时才可选。必须另有说明。

在您的情况下,您必须指定Competitor.class或将其保留。您必须指定JoinTable注释以及joinColumninverseJoinColumn值,因为要搜索的默认JoinTableCompetitor_Competition

@OneToMany
@JoinTable(name = "CompetitionCompetitors", inverseJoinColumns={@JoinColumn(name="competitorId")}, joinColumns={@JoinColumn(name="competitionid")}
private Set< Competitor > competitors = new TreeSet< Competitor >();

如果你正在做的就是查看那些值,我不确定为什么要执行这些更新语句。