【发布时间】:2020-03-25 16:20:56
【问题描述】:
我有一个包含项目描述的表格。物品的价格历史可能非常广泛。正是最后一点让我避免使用带有延迟加载的普通一对多 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 对象的某种代理?
【问题讨论】:
-
基于cmets,我发了一个后续问题,stackoverflow.com/questions/60856510/…
标签: java spring hibernate autowired