How to persist a Map<String, List<Object>> in Hibernate

风流意气都作罢 提交于 2019-12-07 17:50:36

问题


I've got a Map containing MyObject instances. The MyObject class uses JPA to persist its fields:

@OneToMany(cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.FALSE)
private Map<String, MyObject> results = new HashMap<String, MyObject>();

We changed the value stored by the Map to a List:

private Map<String, List<MyObject>> results = new HashMap<String, List<MyObject>>();

But upon launching we receive a stack trace:

Caused by: org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.me.myapp.MyObject.results[java.util.List]
    at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1150)
    at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:680)
    at org.hibernate.cfg.annotations.MapBinder$1.secondPass(MapBinder.java:107)
    at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:66)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1221)
    at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:383)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1206)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:673)
    at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334)
    ... 30 more

Does Hibernate not support persisting a Map containing (as values) List types? Or are my annotations incorrect? I haven't found this particular configuration in any of the documentation or examples.


回答1:


The objects stored in the map must be the target object of the oneToMany association (always mapped). You can't store arbitrary objects or collections there.




回答2:


Personally, I don't think this is a good use of Hibernate. There's no abstraction here. It would make sense if you had a model object with a one-to-many relation expressed as a child List as a data member in the parent.

My advice? Don't use Hibernate. Use straight JDBC, Spring's JDBC template, or something like iBatis.

ORM stands for "Object Relational Mapping". You have tables, so you've got the relational part. You've got data that you can assign to columns in tables.

But it sounds to me like you've got no Objects. So why use Hibernate?



来源:https://stackoverflow.com/questions/9283966/how-to-persist-a-mapstring-listobject-in-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!