java - Hibernate @Entity 与非列对象的 Spring @Autowired 冲突
问题描述
我有一个包含项目描述的表。物品的价格历史可能非常广泛。正是最后一点让我避免使用带有延迟加载的普通一对多 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
注释来指示它不应该被持久化到数据库中。
一般来说,我认为如果这是一个实体,它不应该有任何不属于它的自动装配缓存,但那是另一回事
推荐阅读
- swift - 在模拟存储库中更改数据库数组 - Swift
- sql - 创建包含过去 365 天日期的查询返回字段
- authentication - 无法使用新创建的用户访问我的服务器
- elasticsearch - Elasticseach:搜索查询中的点
- html - 当 onBlur 事件上的按钮消失时,如何使表单提交工作?反应,下一个js
- javascript - 从 Firestore 获取一个空数组
- java - Jetty9 请求大小统计
- c# - 如何在 c# 中获取 sql clr 严格的安全值(使用 SMO dll)
- html - 即使我的表格单元格比表格标题小,我如何让我的行有边框
- maven - Junit5 测试覆盖率为 0%