代码之家  ›  专栏  ›  技术社区  ›  Shervin Asgari

如何为collectionFeElements创建自定义查询

  •  2
  • Shervin Asgari  · 技术社区  · 14 年前

    创建自定义查询时遇到问题。

    这是什么实体:

    @Entity
    public class ApplicationProcess {
    
        @CollectionOfElements
        private Set<Template> defaultTemplates;
        //more fields
    }
    

    @Embeddable
    @EqualsAndHashCode(exclude={"used"})
    public class Template implements Comparable<Template> {
    
     @Setter private ApplicationProcess applicationProcess;
     @Setter private Boolean used = Boolean.valueOf(false);
    
     public Template() {
     }
    
     @Parent
     public ApplicationProcess getApplicationProcess() {
       return applicationProcess;
     }
    
     @Column(nullable = false)
     @NotNull
     public String getName() {
       return name;
     }
    
     @Column(nullable = true)
     public Boolean isUsed() {
       return used;
     }
    
     public int compareTo(Template o) {
       return getName().compareTo(o.getName());
     }
    }
    

    我想创建一个update语句。我试过这两种方法:

    int v = entityManager.createQuery("update ApplicationProcess_defaultTemplates t set t.used = true " + "WHERE t.applicationProcess.id=:apId").setParameter("apId", ap.getId())
       .executeUpdate();
    

    ApplicationProcess_defaultTemplates is not mapped [update ApplicationProcess_defaultTemplates t set t.used = true WHERE t.applicationProcess.id=:apId]

     int v = entityManager.createQuery("update Template t set t.used = true " + "WHERE t.applicationProcess.id=:apId").setParameter("apId", ap.getId())
       .executeUpdate();
    

    同样的错误:

    Template is not mapped [update Template t set t.used = true WHERE t.applicationProcess.id=:apId]

    有什么想法吗?

    更新

    int v = entityManager.createNativeQuery("update ApplicationProcess_defaultTemplates t set t.used=true where t.ApplicationProcess_id=:apId").setParameter("apId", ap.getId()).executeUpdate();
    
    3 回复  |  直到 11 年前
        1
  •  2
  •   Thierry    14 年前

    在hql中不可能执行您想要执行的操作:因为嵌入的对象不是实体,所以它们不能出现在hql查询的from子句中。要更新该对象,需要它位于from子句中。

    所以你有两种可能:

    • 或者使用sql查询(注意了解sql更新对当前会话实体的影响(缺少)
    • 将模板类重构为实体
        2
  •  0
  •   sblundy    14 年前

    我觉得你不行。Hibernate只允许更新实体,不允许嵌入或映射超类。要获得模板,您需要加入,但HQL更新中不允许加入。这是来自 HQL docs

    没有连接,无论是隐式的还是显式的, 子查询可用于 它们本身可能包含连接。

        3
  •  0
  •   Pascal Thivent    14 年前

    可嵌入 不能 Id (设置一个backref到所属类将不可能)。

    或者通过 EntityManager Template 一个实体。