How to have 2 collections of the same type in JPA?

好久不见. 提交于 2019-11-30 06:44:32

This is one of the many Hibernate bugs (HHH-3410 to be precise).

I've managed to fix it by adding @JoinTable annotations to @OneToMany relationships, each having its own table name.

In your case it would look like this:

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name="entity_descriptioncomments")
@IndexColumn(base = 1, name = "dnr")
private List<Comment> descriptionComments = new ArrayList<Comment>();

@OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name="entity_postmortemcomments")
@IndexColumn(base = 1, name = "pmnr")
private List<Comment> postMortemComments = new ArrayList<Comment>();

Note: you must add @IndexColumn annotation as well (because of the other Hibernate issue with multiple EAGER bags: HHH-1718/EJB-346).

DataNucleus

To store 2 collections like that in JPA with DataNucleus (http://www.datanucleus.org) you would do exactly as you've done. You have no @JoinTable annotation hence a FK should be placed in Comment for each of the collections. If you actually do have @JoinTable somewhere (or XML equivalent) then setting the names of the respective join tables (one for each collection) would work too (so they have their own join table). Having a shared join table between 2 collections is possible in DataNucleus too, but that's not standard JPA, instead a vendor extension.

How that maps to Hibernate I've no idea, but then this is JPA so should be consistent since thats the point of having a spec ;-)

There is a flaw with current mapping from data model/domain model point of view: you actaully have a single @OneToMany relationship between Entry and Comment. And Comment entity should have one more attribute called type that takes 2 values: 'description' or 'postMortem'.

To be inline with your current implementation of Entry entity you may want to consider breaking down Comment entity into 2 different entities (possibly using JPA inheritance features) and using @JoinTable annotation in Entry.

If all you care about is ordering, how about configuring the two index column definitions to have the same name?

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