【问题标题】:How can I retrieve data for an Entity based on a column from another entity using spring data JPA?如何使用 Spring Data JPA 根据来自另一个实体的列检索实体的数据?
【发布时间】:2018-01-06 15:54:39
【问题描述】:

我有一个目标表、一个比赛表和一个比赛表。 每个目标都有一个 matchId,每个比赛都有一个 CompetitionId,所以如果我想从比赛中检索所有目标,我会这样做:

select * from mydb.goal g
JOIN mydb.matches m
ON g.goal_match = m.matchid
JOIN mydb.competitions c
ON m.competition = c.competitionid
WHERE c.competitionid = 219; 

我有一个 Spring data JPA 项目,我有 3 个实体这是目标:

@Entity
public class Goal {

@Id
private long idgoal;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "goalMatch")
private Match goalMatch;

public long getIdgoal() {
    return idgoal;
}

public void setIdgoal(long idgoal) {
    this.idgoal = idgoal;
}

public Match getGoalMatch() {
    return goalMatch;
}

public void setGoalMatch(Match goalMatch) {
    this.goalMatch = goalMatch;
}

}

这是比赛

@Entity(name = "matches")
public class Match {

@Id
@GeneratedValue
private long idmatch;
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "competition")
private Competition competition;

public long getIdmatch() {
    return idmatch;
}

public void setIdmatch(long idmatch) {
    this.idmatch = idmatch;
}

public Competition getCompetition() {
    return competition;
}

public void setCompetition(Competition competition) {
    this.competition = competition;
}

}

和竞争:

@Entity(name = "competitions")
public class Competition {

@Id
private Long idcompetitions;

public Long getIdcompetitions() {
    return idcompetitions;
}
public void setIdcompetitions(Long idcompetitions) {
    this.idcompetitions = idcompetitions;
}
}

然后我有我的目标存储库,我试图找到一种方法来从比赛中检索所有目标,但我找不到方法来做到这一点,除非使用很长的 @Query。

Spring Data JPA 是否有直接的方式来做到这一点? 还是我应该只使用自定义 @Query?

【问题讨论】:

  • @Query("select g from Goal g where g.goalMatch.competition.id = :competitionId")。这是非常基本的东西。您需要阅读 Hibernate 手册,尤其是关于 JPQL / HQL 的章节。

标签: hibernate spring-data spring-data-jpa


【解决方案1】:

JB Nizet 非常接近:

正确的查询是:

@Query("select g from Goal g where g.goalMatch.competition.idcompetitions = :competitionId")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 2021-05-25
    • 2012-08-06
    • 1970-01-01
    相关资源
    最近更新 更多