簡體   English   中英

非列對象的 Hibernate @Entity 與 Spring @Autowired 沖突

[英]Hibernate @Entity conflict with Spring @Autowired for non-column object

我有一個包含項目描述的表格。 物品的價格歷史可能非常廣泛。 正是最后一點讓我避免使用帶有延遲加載的普通一對多 Hibernate 映射。 想想一個價格歷史,比如證券交易所的報價,有很多歷史。

所以我有一個運行良好的緩存,它全部與 Spring 連接,注入了 DAO,緩存管理需要查詢的內容與它已經知道的內容。

因此,“自然”的事情是能夠詢問商品的價格歷史記錄。 這是一些代碼,它是真實事物的精簡版:

@Entity @Table(name="item")
public class Item {
    @Id
    @Column(name="id")
    private long id;
    @Column(name="name")
    private String name;

    @Autowired
    private PriceCache priceCache;

    /* ...setters, getters for id, name ... */

    public NavigableMap<LocalDateTime,SecurityValue> getPrices(LocalDateTime begTime, LocalDateTime endTime) {
        return priceCache.get(id, begTime, endTime);
    }
}

我的原始版本使用 PriceCache 的所有靜態方法; 我想切換到使用注入 bean 的部分原因是,這意味着我可以將緩存重寫為接口的實現,這使得為示例中沒有的某些位設置單元測試變得更加容易; 我可以創建一個測試緩存對象,以我需要的任何方式提供我的價格歷史記錄,而無需訪問數據庫。

問題是當 Spring 和 Hibernate 掃描包時,它們似乎在如何處理 @Autowired 字段上發生沖突; 為了便於閱讀,我得到了以下一些格式); dbEMF 是我的 EntityManagerFactory:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException:
   Error creating bean with name 'dbEMF' defined in class path resource [applicationContext.xml]:
     Invocation of init method failed;
   nested exception is javax.persistence.PersistenceException:
     [PersistenceUnit: default] Unable to build Hibernate SessionFactory;
   nested exception is org.hibernate.MappingException:
     Could not determine type for: com.example.cache.PriceCache, at table: item, for columns: [org.hibernate.mapping.Column(priceCache)]

同樣,如果我只對 PriceCache 使用靜態方法,則基本代碼和緩存工作正常,我在其中“手動”將其創建為單例。 將它轉換為讓 Spring 處理其他地方的創建和注入工作也很好。 只有當我混合使用 Hibernate 和 Spring 時才會遇到問題。

我還沒有嘗試過使用外部 XML 文件進行休眠配置,這可能會解決問題,或者不能。

有沒有辦法告訴 Hibernate 這不是列? 或者我應該遵循不同的模式來做這種事情,也許是 Item 對象的某種代理?

您可以使用@Transient批注,指示不應將其持久化到數據庫中。

一般來說,我認為如果這是一個實體,它不應該有任何不屬於它的自動裝配緩存,但這是另一回事

關於下面答案中的討論。 Hibernate 集合和實體都是代理對象。 也許您可以嘗試實現一個自定義 HibernateProxy 來管理您的集合。 根據文檔,它似乎是可能的(CustomProxies),但我從未在這里檢查過: https : //docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#entity-proxy

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM