具有嵌入式id的Hibernate条件查询提取

时间:2017-11-07 16:37:16

标签: java hibernate jpa hibernate-criteria

我有这个<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>Title</h1> <div class="cctrl"> <form> <input type="text" value="Bla bla"> <input type="text" value="Bla bla"> <fieldset> <input class="button" type="submit" value="submit"> </fieldset> </form> </div> <h1>John</h1> <div class="cctrl"> <form> <input type="text" value="Bla bla"> <input type="text" value="Bla bla"> <fieldset> <input class="button" type="submit" value="submit"> </fieldset> </form> </div> <h1>Title</h1> <div class="cctrl"> <form> <input type="text" value="Bla bla"> <input type="text" value="Bla bla"> <fieldset> <input class="button" type="submit" value="submit"> </fieldset> </form> </div> <h1>John</h1> <div class="cctrl"> <form> <input type="text" value="Bla bla"> <input type="text" value="Bla bla"> <fieldset> <input class="button" type="submit" value="submit"> </fieldset> </form> </div>课程:

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 queryUser,因为我需要阅读他们的一些属性:

Tournament

但是我收到了错误:

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 上的关系以访问它们?

1 个答案:

答案 0 :(得分:0)

尝试

@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();