Product.java
@Entity @Table(name="product") public class Product {
// ...
@ManyToOne @JoinColumn(name="product_id")
private Brand brand;
// getters and setters
}
Brand.java
@Entity @Table(name="brand") public class Brand {
// ....
@OneToMany(mappedBy="brand", cascade = CascadeType.ALL)
private Set<Product> products;
}
BrandRepository.java
@Repository public interface BrandRepository extends JpaRepository<Brand, Long>{}
BrandController.java
@RestController @RequestMapping("/api/v1")
public class BrandController {
@Autowired private BrandRepository brandRepository;
@GetMapping("/brands")
public List<Brand> getAllBrands(){
return brandRepository.findAll();
}
@GetMapping("/brand/{id}")
public ResponseEntity<Brand> getBrand(@PathVariable(value="id") Long bid) throws ResourceNotFoundException {
Brand brand = brandRepository.findById(bid).orElseThrow(() -> new ResourceNotFoundException("user not found"+bid));
return ResponseEntity.ok().body(brand);
}
}
whenever i am trying to access /brands or /brand/1 , i am getting repeated json results like this:
for "http://127.0.0.1:8080/api/v1/brands"
[{"id":1,"name":"Apple","products":[{"id":4,"name":"Apple kndsksk ksjdsoijd sd","price":"2893787","brand":{"id":1,"name":"Apple","products":[{"id":4,"name":"Apple kndsksk ksjdsoijd sd","price":"2893787","brand":{"id":1,"name":"Apple","products":[{"id":4,"name":"Apple kndsksk ksjdsoijd sd","price":"2893787","brand":{"id":1,"name":"Apple","products":[{"id":4,"name":"Apple
... and continues
for "http://127.0.0.1:8080/api/v1/brand/1"
{"id":1,"name":"Apple","products":[{"id":1,"name":"Apple kksf sfok sokoak","price":"9239932","brand":{"id":1,"name":"Apple","products":[{"id":1,"name":"Apple kksf sfok sokoak","price":"9239932","brand":{"id":1,"name":"Apple","products":[{"id":1,"name":"Apple kksf sfok sokoak","price":"9239932","brand":{"id":1,"name":"Apple","products":[{"id":1,"name":"Apple kksf sfok sokoak","price":"9239932","brand":{"id":1,"name":"Apple","products":[{"id":1,"name":"Apple kksf sfok sokoak","price":"9239932","brand":{"id":1,"name":"Apple","products":[{"id":1,"name":"Apple kks
... and continues