5

I have this Entity class:

@Entity
public class Registered implements Serializable {

    @Id
    public RegisteredId id;
}

With this EmbeddedId:

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

}

I'm trying to make this Criteria query fetching the User and the Tournament because I need to read some of their attributes:

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

But I'm getting an error:

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

What I'm doing wrong? How can I fetch the relations on an EmbeddedId to access them?

Tom
  • 977
  • 11
  • 18
Atropo
  • 12,231
  • 6
  • 49
  • 62
  • Have you tried to extract variable as `root.alias("id")` and fetch on it? `Selection id = root.alias("id"); id.fetch("user", JoinType.LEFT);`? – Andremoniy Dec 07 '17 at 17:49

2 Answers2

1
root.fetch("id", JoinType.LEFT).fetch("user", JoinType.LEFT);
root.fetch("id", JoinType.LEFT).fetch("tournament", JoinType.LEFT);
Italo Brenner
  • 128
  • 1
  • 7
0

Try with

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

and

@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;
}

and then

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();
Glapa
  • 790
  • 10
  • 20