TreeMap字段注入PersistentSortedMap引发IllegalArgumentException求助
解决Hibernate中TreeMap与PersistentSortedMap类型不匹配问题
问题原因
Hibernate会对实体类里的集合字段做代理增强:
- 之前用
Map当字段类型时,Hibernate生成的PersistentMap代理类实现了Map接口,类型匹配所以运行正常。 - 换成
TreeMap后,Hibernate会用PersistentSortedMap(它实现了SortedMap接口)来代理,但PersistentSortedMap并不是TreeMap的子类,直接给TreeMap类型的字段赋值就会触发类型转换错误,也就是你碰到的Can not set java.util.TreeMap field to org.hibernate.collection.spi.PersistentSortedMap。
解决方案
最稳妥的做法是面向接口编程,把字段类型换成SortedMap(TreeMap本身就实现了这个接口),具体修改如下:
- 调整字段定义:
private SortedMap<Round, Integer> points;
- 构造方法保持不变,依旧用
TreeMap初始化:
this.points = new TreeMap<>();
- 修改Setter方法的参数类型为
SortedMap:
public void setPoints(SortedMap<Round, Integer> points) { this.points = points; }
这样Hibernate的PersistentSortedMap代理类就能正常赋值给SortedMap类型的字段,同时依然保留TreeMap的排序特性(实际初始化的是TreeMap,Hibernate代理会维持这个行为)。
如果非要强制用TreeMap作为字段类型,可以在字段上添加@CollectionType注解指定Hibernate使用TreeMap的实现,但这种方式灵活性差,不推荐。
内容的提问来源于stack exchange,提问作者abdlost
相关产品推荐
相关产品推荐

