title: Recursive JSON view of an entity with one-to-many relationship in REST controller
body: <p>I'm using SpringBoot and JPA to build a REST interface. </p>
  
  <p>Now, I have a strange JSON returned for the list of products fetched from the database. Let's say that I have:</p>
  
  <pre><code>@Entity
  public class Product {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;
  
      @ManyToOne(optional = false, fetch = FetchType.LAZY)
      @JoinColumn(name = "categoryId", nullable = false, updatable = false)
      private Category category;
  
      ...
  }
  
  @Entity
  public class Category implements Serializable {
  
      @Id
      @GeneratedValue(strategy = GenerationType.AUTO)
      private Long id;
  
      @OneToMany(mappedBy = "category", cascade = CascadeType.DETACH)
      @OrderBy("name ASC")
      private List&lt;Product&gt; products = Collections.emptyList();
  
      ...
  }
  </code></pre>
  
  <p>The JPA repository for the <code>Product</code> is defined as:</p>
  
  <pre><code>public interface ProductRepository extends JpaRepository&lt;Product, Long&gt; {
      List&lt;Product&gt; findAll();
  }
  </code></pre>
  
  <p>In my controller I have:</p>
  
  <pre><code>@Autowired
  private ProductRepository productRepo;
  
  @RequestMapping("/all-products", method = RequestMethod.GET)
  public Map&lt;String,Object&gt; home() {
      Map&lt;String,Object&gt; model = new HashMap&lt;String,Object&gt;();
      model.put("products", productRepo.findAll());
      return model;
  }
  </code></pre>
  
  <p>What is driving my crazy, is that if I try to call this service as follows:</p>
  
  <pre><code>$ curl localhost:8080/all-products
  </code></pre>
  
  <p>I get a recursive output due to the relationship between tables <code>product</code> and <code>category</code>, e.g.:</p>
  
  <pre><code>{"products":[{"id":1,"name":"Product1","category":
  {"id":1,"name":"Cat1","products":[{"id":6,"name":"Product6","category":
  {"id":1,"name":"Cat1","products":[{"id":6,"name":"Product6","category":
  {"id":1,...
  </code></pre>
  
  <p>What am I doing wrong?</p>