Spring JPA - Multiply nested tables applying WHERE clause

本小妞迷上赌 提交于 2020-01-25 07:53:22

问题


I already created question before which was complicated. So I am creating a new one which will be as simple as possible.

I am having a problem with Spring JPA especially twice nested structure.

Here is a super simple relationship diagram:

The country has multiple rivers and rivers can flow through multiple countries. The river has multiple bridges but the bridge can be built over 1 river only. So M:N -> 1:N

This is the expected result:

{
  countries: [
    {
      countryID: 1,
      rivers: [
        {
          riverID: 1,
          bridges: [{
            bridgeID: 1
          }]
        }
      ]
    }
  ]
}

And this is what I have.

Country entity

public class Country {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    ... more columns

    @ManyToMany(fetch = FetchType.EAGER,
            cascade = {
                    CascadeType.PERSIST,
                    CascadeType.MERGE
            })
    @JoinTable(name = "country_river",
            joinColumns = { @JoinColumn(name = "countryid") },
            inverseJoinColumns = { @JoinColumn(name = "riverid") })
    private Set<River> rivers = new HashSet<>();

River entity

public class River {
    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    ... more columns


    @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.REMOVE)
    @JoinColumn(name = "riverid")
    private Set<Bridge> Bridges;

Don't need to mention Bridge entity since there is only ID column specified ( I am using unidirectional relation)

The problem is, that bridges are not filtered based on country. As you can see in the expected output, I would like to list all countries and it's associated rivers and bridges on them in the given country.

Do I have to create a custom query on Bridges inside River entity (If so, how.)? Or do I have to somehow change the structure of the database?

来源:https://stackoverflow.com/questions/59614479/spring-jpa-multiply-nested-tables-applying-where-clause

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