java – 带有嵌入式id的Hibernate条件查询提取

我有这个Entity类:

@Entity
public class Registered implements Serializable {

    @Id
    public RegisteredId id;
}

有了这个EmbeddedId:

@Embeddable
public class RegisteredId implements Serializable {
    @ManyToOne
    public User user;
    @ManyToOne
    public Tournament tournament;

}

我正在尝试使用此Criteria查询获取用户和锦标赛,因为我需要阅读他们的一些属性:

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Registered> criteria = builder.createQuery(Registered.class);
Root<Registered> root = criteria.from(Registered.class);
root.fetch("id.user", JoinType.LEFT);
root.fetch("id.tournament", JoinType.LEFT);
criteria.where(builder.equal(root.get("id.tournament.id"), idTournament));
List<Registered> registereds = em.createQuery(criteria).getResultList();

但我收到一个错误:

Execution exception[[CompletionException: java.lang.IllegalArgumentException: Unable to locate Attribute  with the the given name [id.user] on this ManagedType

我做错了什么?
如何获取EmbeddedId上的关系以访问它们?

最佳答案
试试吧

@Embeddable
public class RegisteredId implements Serializable {
    public Long userId;
    public Long tournamentId;
}

@Entity
public class Registered implements Serializable {

    @EmbeddedId
    public RegisteredId id;

    @ManyToOne
    @JoinColumn(name = "userId", updatable = false, insertable = false)
    public User user;
    @ManyToOne
    @JoinColumn(name = "tournamentId", updatable = false, insertable = false)
    public Tournament tournament;
}

然后

CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Registered> criteria = builder.createQuery(Registered.class);
Root<Registered> root = criteria.from(Registered.class);
root.fetch("user", JoinType.LEFT);
root.fetch("tournament", JoinType.LEFT);
criteria.where(builder.equal(root.get("id.tournamentId"), idTournament));
List<Registered> registereds = em.createQuery(criteria).getResultList();

转载注明原文:java – 带有嵌入式id的Hibernate条件查询提取 - 代码日志