2016-02-26 166 views
1

我在Hibernate 4.3.7中使用@Formula註釋,但它不加載值。休眠@Formula註釋不起作用

@Entity 
@AccessType(Type.PROPERTY) 
@Table(name = "ENTITY_B_TABLE") 
public class EntityB extends AbstractEntity { 
    // 
    // ... 
    // 

    private EntityB parentEntityB; 

    @Formula(value = "SELECT * FROM ENTITY_B_TABLE WHERE TYPE IN ('A', 'B', 'C') AND ROWNUM=1 CONNECT BY PRIOR PARENT_ID = ID START WITH ID = :id") 
    public EntityB getParentEntityB() { 
     return parentEntityB; 
    } 

    public void setParentEntityB(EntityB parentEntityB) { 
     this.parentEntityB = parentEntityB; 
    } 

} 

在這種情況下,我有一個錯誤:

Caused by: org.hibernate.MappingException: Could not determine type for: my.package.EntityB, at table: ENTITY_B_TABLE, for columns: [org.hibernate.mapping.Formula( SELECT * FROM ENTITY_B_TABLE WHERE LEVEL_NAME IN ('A', 'B', 'C') AND ROWNUM=1 CONNECT BY PRIOR PARENT_ID = ID START WITH ID = :id)]

在SQL 「ID」 是當前EntityB的ID。 如果我將@Transient註釋添加到getParentEntityB方法,則沒有錯誤,但parentEntityB爲空。 ENTITY_B_TABLE中沒有parentEntityB列,我們不想創建它,我們想要動態加載它。並且我們可以保證parentEntityB根據select而不是null。

有沒有更好的方法來解決這個問題? (我也試過@Loader沒有成功)

Try to move @Formula over the field. In my previous experience, I saw a > lot of them being only over fields.

結果是一樣的。

I found somethinf like this: forum.hibernate.org/viewtopic.php?f=1&t=956537 - maybe that could help? In short - @OneToOne may be required.

隨着(@OneToOne或@ManyToOne),並沒有@Transient沒有什麼異常,但仍parentEntityB等於空。

+0

試着在場上移動@Formula。在我以前的經歷中,我看到他們中的很多人只是在田野上。 – mlewandowski

+0

謝謝,我已經嘗試過相同的結果。 – egorlitvinenko

+0

我發現了這樣的東西:https://forum.hibernate.org/viewtopic.php?f=1&t=956537 - 也許這可能有幫助嗎?總之 - 可能需要@OneToOne。 – mlewandowski

回答

0

我懷疑公式是否可用於返回實際對象。 從文檔,它看起來像它返回原始的只讀值僅

@Formula("obj_length * obj_height * obj_width") 

衆長getObjectVolume()

再舉一個例子,但同樣只能返回原始值。

<property name="totalPrice" 
formula="(SELECT SUM (li.quantity*p.price) FROM LineItem li, Product p 
      WHERE li.productId = p.productId 
      AND li.customerId = customerId 
      AND li.orderNumber = orderNumber)"/> 
+0

http://stackoverflow.com/questions/7098722/hibernate-load-entities-with-formula – egorlitvinenko