gpt4 book ai didi

java - JPA 2 Criteria 与抽象集合相结合

转载 作者:行者123 更新时间:2023-12-01 09:24:19 25 4
gpt4 key购买 nike

有没有办法使用 Criteria API 将类 Player 与 Manager 加入层次结构中,如下所示?我想在我的 DAO 中找到具有给定 ID 的经理的所有玩家,并尝试如下操作:

查询:

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Player> query = cb.createQuery(Player.class);
Root<Player> root = query.from(Player.class);

Join<Player, PlayerTeam> playerTeamJoin = root.join(Player_.playerTeam);
Join<PlayerTeam, PlayerTeamAssignment> playerTeamAssignmentJoin = playerTeamJoin.join(PlayerTeam_.playerTeamAssignments);

// Desired statement:
Predicate predicate = cb.equal(playerTeamAssignmentJoin.get(ManagerAssignment_.manager), manager);

类层次结构:

@Entity
class Player {
@OneToOne(mappedBy = "player")
PlayerTeam playerTeam;
}

@Entity
class PlayerTeam {
@JoinColumn(name = "PLAYER_ID", referencedColumnName = "ID")
Player player;
@OneToMany(mappedBy = "playerTeam")
Collection<PlayerTeamAssignment> playerTeamAssignments;
}

@Entity
@DiscriminatorColumn(name = "ASSIGNMENT_TYPE", discriminatorType = DiscriminatorType.STRING)
public abstract class PlayerTeamAssignment { // It has three implementations
@ManyToOne
@JoinColumn(name = "PLAYER_TEAM_ID", referencedColumnName = "ID")
PlayerTeam playerTeam;
}

@Entity
@DiscriminatorValue("INDIVIDUAL")
public class ManagerAssignment extends PlayerTeamAssignment {
@ManyToOne
@JoinColumn(name = "MANAGER_ID", referencedColumnName = "ID")
Manager manager; // id inside
}

最佳答案

我已经找到了解决我的问题的方法。我必须使用路径

Join<Player, PlayerTeam> playerTeamJoin = root.join(Player_.playerTeam);
Join<PlayerTeam, PlayerTeamAssignment> playerTeamAssignments = root.join(PlayerTeam_.playerTeamAssignments);
Path managerPath = ((Path) playerTeamAssignments.as(ManagerAssignment.class)).get(ManagerAssignment_.manager));

您可以在谓词中使用它:

 Predicate predicate = cb.equal(managerPath.get(Manager_.globalId), managerId);

关于java - JPA 2 Criteria 与抽象集合相结合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39960106/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com