简体   繁体   中英

JPA annotations with bidirectional relationship of superclass

I'm trying to add JPA annotations to my model.

Here's a part of my superclass:

@Entity
@Table(name="destinations")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Destination {
    protected abstract Destination getParent();
    protected abstract Set<Destination> getChildren();
}

And these are the implementations:

@Entity
@DiscriminatorValue(value = "country")
public class Country extends Destination {
    private Set<Destination> regions;
    private Set<Destination> cities;

    @Override
    public Destination getParent() {
        return null;
    }

    @Override
    public Set<Destination> getChildren() {
        if (regions != null && !regions.isEmpty()) {
            return regions;
        }
        return cities;
    }
}

@Entity
@DiscriminatorValue(value = "region")
public class Region extends Destination {
    private Set<Destination> cities;
    private Country country;

    @Override
    public Destination getParent() {
        return country;
    }

    @Override
    public Set<Destination> getChildren() {
        return cities;
    }
}

@Entity
@DiscriminatorValue(value = "city")
public class City extends Destination {
    private Country country;
    private Region region;

    @Override
    public Destination getParent() {
        if (region != null) {
            return region;
        }
        return country;
    }

    @Override
    public Set<Destination> getChildren() {
        return null;
    }
}

So there are Countries that have Regions with Cities in it, and Countries without Regions but with Cities.

How do I annotate these classes so their bidirectional relationships can be persist and all the Destinations are in a single table?

  • Ideally as my understanding the design should have been this way

    Country <----> City

    Country <----> Region

    City <----> Region

  • Considering that region can be or cannot exist we need to have Country to City mapping mandatory and optional mapping related to Region.

  • Now as per your requirement where in you need all of them associated to Destination which means as per the current design shown above you will have multiple values

  • for eg. Country(IND)-Region(MH)-City(MUM); Then you would 2 rows in destination one for Country-City and other Country-Region

  • Hence my final conclusion is that if you go for Inheritance Design you will end up having multiple rows as explained in the previously example and if you simply use OneToOne/OneToMany mapping as shown in point you persist twice once for Country-City and Country-Region

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM