I want to use criteria to make the following query. I have an Entity with EmbeddedId defined:
@Entity
@Table(name="TB_INTERFASES")
public class Interfase implements Serializable {
@EmbeddedId
private InterfaseId id;
}
@Embeddable
public class InterfaseId implements Serializable {
@Column(name="CLASE")
private String clase;
}
And the criteria query that i am trying to do is:
CriteriaBuilder criteriaBuilder = this.entityManager.getCriteriaBuilder();
CriteriaQuery<Interfase> criteriaQuery = criteriaBuilder.createQuery(Interfase.class);
Root<Interfase> entity = criteriaQuery.from(Interfase.class);
criteriaQuery.where(
criteriaBuilder.equal(entity.get("clase"), "Clase"),
);
But this is throwing an IllegalArgumentException:
java.lang.IllegalArgumentException: Not an managed type: class InterfaseId
i've tried with this queries too:
Root<Interfase> entity = criteriaQuery.from(Interfase.class);
criteriaQuery.where(
criteriaBuilder.equal(entity.get("id").get("clase"), "Clase"),
);
and this one too...
Root<Interfase> entity = criteriaQuery.from(Interfase.class);
criteriaQuery.where(
criteriaBuilder.equal(entity.get("id.clase", "Clase"),
);
with no luck. So my question is how can i make a query with criteria when my classes are using Embedded and EmbeddedId annotations?
Thanks!. Mauro.
It is an old question, but anyway...
Another extremely simple solution is
Except if you trying to do something else besides what you asked, this is the "sane" way to do it. A query on the id will return maximum one result.
You need to use path navigation to access the attribute(s) of the
Embeddable
. Here is an example from the JPA 2.0 specification (using the static metamodel):So in your case, I think you'll need something like this:
References
Update: I've tested the provided entities with Hibernate EntityManager 3.5.6 and the following query:
runs fine and generates the following SQL:
Works as expected.
Try to copy and paste the
metamodel
classes into the same folder where your entities are saved (in NetBeans 8.2 they are automatically generated and have the same name of your entity but with an underscore at the end. Should be something likeInterfase_
andInterfaseId_
).Force the import of the
metamodel
classesInterfase_
andInterfaseId_
and refer to the desired field.