@MappedSuperclass and @OneToMany

UML diagram

I need a OneToMany association from the country to the Place superclass (@MappedSuperclass). It can be bidirectional. I need something like @OneToAny ...

@MappedSuperclass public class Place { private String name; private Country country; @Column public String getName() { return name; } public void setName(String name) { this.name = name; } @ManyToOne @JoinColumn(name="country_id") public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } } 

Country:

 @Entity public class Country { private long id; private String name; private List<Place> places; @Any(metaColumn = @Column(name = "place_type"), fetch = FetchType.EAGER) @AnyMetaDef(idType = "integer", metaType = "string", metaValues = { @MetaValue(value = "C", targetEntity = City.class), @MetaValue(value = "R", targetEntity = Region.class) }) @Cascade({ org.hibernate.annotations.CascadeType.ALL }) //@JoinColumn(name="unnecessary") //@OneToMany(mappedBy="country") // if this, NullPointerException... public List<Place> getPlaces() { return places; } //and rest of class 

Without @JoinColunm there is an exception

 Caused by: org.hibernate.AnnotationException: @Any requires an explicit @JoinColumn(s): tour.spring.bc.model.vo.Country.places 

In the table City and Region there is a foreign key to the table Country (Region.country_id, City.country_id), which is in order. But I don't need the foreign key in the Country table for the Region and City tables, so I don't need @JoinColum.

I have searched for a solution a lot, but it seems that there is no good solution.

+4
source share
1 answer

@Any does not make sense here, since the foreign key is on the Place side, and therefore it does not need an additional meta column.

I'm not sure if it is possible to create a polymorphic relation to @MappedSuperclass . However, you can try to declare Place as @Entity @Inheritance(InheritanceType.TABLE_PER_CLASS) , it should create the same database schema and allow polymorphic relationships.

+5
source

Source: https://habr.com/ru/post/1336608/


All Articles