criteria-api在MapJoin的where子句中设置谓词



我在设置以下查询的where子句时遇到一些问题:

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

我基本上是在尝试获取组件Map中包含一个条目的所有配置,该条目的键包含"abc",其值包含"def"。基于来自http://blogs.oracle.com/ldemichiel/entry/java_persistence_2_0_proposed,Maps节,但显然我遗漏了一些东西。

实体结构如下:

@Entity
public class Configuration{
  @Id
  protected Long id;       
  @OneToMany
   protected Map<String, Component> components;
}

@Entity
public class Component{
    @Id
    protected Long id;    
    protected String displayName;
}

提前感谢您,如有任何帮助,不胜感激。

您得到了什么错误?

您的代码没有意义。默认情况下,在JPA中,Map键被认为来自目标对象,如果你没有使用@MapKey设置用于键的目标字段,那么默认情况下它被认为是对象的Id。在这种情况下,你的键是String,Id是Long,所以我根本看不到这一点?

您需要提供一个@MayKey或@MapKeyColumn来将键独立存储在联接表中。

最新更新