Implementing hierarchical data structures with JPA (fixed depth) Implementing hierarchical data structures with JPA (fixed depth) postgresql postgresql

Implementing hierarchical data structures with JPA (fixed depth)


You can avoid the 3 extra mapping tables by using the @JoinColumn annotation rather than the @JoinTable annotation that I suspect you are using.

So for example:

COUNTRY

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy="country")private List<State> stateList;

STATE

@ManyToOne@JoinColumn(name="country_id")private Country country

The database tables would be as follows:

Country

country_id => primary key

State

state_id => primary keycountry_id => foreign key

This way the mapping tables between all the 4 entities can be avoided.


You can achieve this pretty easily using JPQL:

SELECT DISTINCT countryFROM Country countryJOIN FETCH country.states statesJOIN FETCH states.counties countiesJOIN FETCH counties.cities citiesWHERE country.id = :countryId

Using fetchType = FetchType.EAGER on @OneToMany/@ManyToOne(believe that one is already EAGER by default) will achieve similar results.


It's very simple use bidirectional mapping. Go through that link

How to delete Child or Parent objects from Relationship?

Make some changes like below

Country Entity:

------@OneToMany(mappedBy="Country ",cascade = CascadeType.ALL)private List<States > states;@OneToMany(mappedBy="Country ",cascade = CascadeType.ALL)private List<Counties> counties;@OneToMany(mappedBy="Country ",cascade = CascadeType.ALL)private List<Cities> cities;-------setters & getters

States Entity:

-----@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)@JoinColumn(name="countryId")      private Country country ;-----

Counties Entity:

-------- @ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @JoinColumn(name="countryId")       private Country country ; -------

Cities Entity:


@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)@JoinColumn(name="countryId")      private Country country ;---------

After compilation of all entity's do your insertion . Only 4 will create and read your data by using Country object id.