1

I have two tables, the first one called regions and it has "region_id","region_name", and the second table is called cities and it has "city_id","city_name","region_id" as FK,

Now when i tried to pull all cities i hit

/cities

//CityController
@RestController
public class City {
    @Autowired
    private CityService cityService;


    @GetMapping(value = "/cities")
    public @ResponseBody
    List<CityEntity> getCities() {
        List<CityEntity> list = cityService.getCities();
        return list;
    }
}

CityEntity is:

@Entity
@Table(name = "cities")
@Getter
@Setter
public class CityEntity {
    @Id
    @Column(name = "city_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "city_name", unique = true)
    private String cityName;
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "region_id")
    private RegionEntity region;

}

and RegionEntity is :

@Entity
@Table(name = "regions")
@Getter
@Setter
public class RegionEntity {
    @Id
    @Column(name = "region_id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name = "region_name", unique = true)
    private String regionName;
}

and the response was

[ { "id": 1, "cityName": "amman", "region": { "id": 1, "regionName": "part1" } }, { "id": 2, "cityName": "zarqa", "region": { "id": 1, "regionName": "part1" } } ]

So far so good

I wanted another API that can pull all regions with their cities so i did something like cityEntity which is i added the bellow method to reagionEntity

 @OneToMany(fetch = FetchType.EAGER)
    @JoinColumn(name = "city_id")
    private List<CityEntity> cities;

but Surprisingly when i rehit

/cities i got Unexpected '' but when i hit it in chrome browser it listed a lot of object like [{"id":1,"regionName":"part1","cities":[{"id":1,"cityName":"amman","region":{"id":1,"regionName":"part1","cities":[{"id":1,"cityName":"amman","region":{"id":1,"regionName":"part1","cities":

it seems that it repeated itself i have no idea why and nothing helped me in spring.io website

My Repository is extending JPARepository and i used findAll() method. Please advice. Thanks in advance

Habooltak Ana
  • 147
  • 1
  • 11
  • +1 looks like a recursion, op is using boot and the built in Jackson should be able to catch the recursion. More reference https://stackoverflow.com/questions/3325387/infinite-recursion-with-jackson-json-and-hibernate-jpa-issue – Monish Sen Feb 14 '18 at 22:20
  • Thanks for your responses guys, i need both, if i hit for cities it should return them with regions ids, and if i need to hit for regions it should display all regions with it's cities :/ – Habooltak Ana Feb 14 '18 at 22:26
  • May be you need to write some more here like , first fetch all the regions and iterate over list and fetch cities for each region similialy for cities as well. – Ramesh Fadatare Feb 15 '18 at 07:32

0 Answers0