2010-06-18 51 views
2

我在創建自定義查詢時遇到問題。如何爲CollectionOfElements創建自定義查詢

這是實體的:

@Entity 
public class ApplicationProcess { 

    @CollectionOfElements 
    private Set<Template> defaultTemplates; 
    //more fields 
} 

而且Template.java

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

我想創建一個更新語句。我曾嘗試這兩個:

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]

任何想法?

UPDATE

我固定它通過創建本地查詢

int v = entityManager.createNativeQuery("update ApplicationProcess_defaultTemplates t set t.used=true where t.ApplicationProcess_id=:apId").setParameter("apId", ap.getId()).executeUpdate(); 

回答

2

你想要做什麼的HQL是不可能的:作爲嵌入對象不是實體,它們不能出現在from子句的hql查詢。爲了更新該對象,您需要將它放在from子句中。

所以,你有兩種可能性:

  • 要麼使用一個SQL查詢(當心知道(缺乏)對當前會話實體SQL更新的影響)
  • 重構你的模板類的實體
0

我不認爲你可以。 Hibernate只允許更新實體,而不是可嵌入的或映射的超類。要訪問模板,您需要加入,但在HQL更新中不允許加入連接。下面是來自HQL docs的relavent限制:

No joins, either implicit or explicit, can be specified in a bulk HQL query. Sub-queries can be used in the where-clause, where the subqueries themselves may contain joins.

你將不得不既可使用本地SQL或檢索和更改在Java代碼中的字段值。

0

Embeddables 不能被直接(散裝與否)查詢,它們不是獨立的對象,因爲他們沒有Id(和backref設置爲所屬類不會使它可能的)。

要麼通過EntityManager來更新擁有對象,要麼讓您的Template成爲實體。