问题
I'm having some trouble with setting the where
clause of the following query:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Configuration> cq = cb.createQuery(Configuration.class);
Root<Configuration> conf = cq.from(Configuration.class);
MapJoin<Configuration, String, Component> mapJoin = conf.join(Configuration_.components, JoinType.LEFT);
cq.where(cb.and(cb.like(mapJoin.key(), "%abc%"),
cb.like(mapJoin.value().get(Component_.displayName), "%def%")));
cq.select(pc);
I am basically trying to get all Configurations that contain an entry in the components-Map whose key contains "abc" and whose value contains "def".
I expected this to work, based on the sample code from http://blogs.oracle.com/ldemichiel/entry/java_persistence_2_0_proposed, section Maps
, but apparently I'm missing something.
The entities have following structure:
@Entity
public class Configuration{
@Id
protected Long id;
@OneToMany
protected Map<String, Component> components;
}
and
@Entity
public class Component{
@Id
protected Long id;
protected String displayName;
}
Thank you in advance, any help appreciated.
回答1:
What error do you get?
Your code does not make sense. By default in JPA the Map key is assumed to come from the target object, and if you don't set the target field to use for the key using @MapKey then by default it is assumed to be the object's Id. In this case your key is a String and Id is a Long, so I can't see this working at all?
You need to give a @MayKey, or a @MapKeyColumn to store the key independently in the join table.
来源:https://stackoverflow.com/questions/9152229/criteria-api-set-predicate-in-where-clause-for-mapjoin