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