在Spring 4.0中使用Jackson2(MVC + REST + Hibernate)

Nik*_*hil 5 java spring json hibernate jackson

我正在制作一个安静的应用程序并尝试将对象列表转换为json以获取特定的URL(@RequestMapping/@ResponseBody)

我的classpath中有jackson-hibernate4和jackson-core,databind等.

这是我想要转换为json的对象.

@Entity
@Table(name="Product")
public class Product {
@Id
@Column(name="productId")
@GeneratedValue
protected int productId;
@Column(name="Product_Name")
protected String name;

@Column(name="price")
protected BigDecimal baseprice;


@OneToMany(cascade = javax.persistence.CascadeType.ALL,mappedBy="product",fetch=FetchType.EAGER)
protected List<ProductOption> productoption = new ArrayList<ProductOption>();

@OneToMany(cascade = javax.persistence.CascadeType.ALL,mappedBy="product",fetch=FetchType.EAGER)
protected List<ProductSubOption> productSubOption = new ArrayList<ProductSubOption>();


@ManyToOne
@JoinColumn(name="ofVendor")
protected Vendor vendor;
Run Code Online (Sandbox Code Playgroud)

Product里面的两个对象也是POJO'S ..

这是我检索产品列表的方法

@Override
public List<Product> getMenuForVendor(int vendorId) {
    List<Product> result = em.createQuery("from "+Product.class.getName()+" where ofVendor = :vendorId").setParameter("vendorId", vendorId).getResultList();
    System.out.println(result.size());
    return result;
}
Run Code Online (Sandbox Code Playgroud)

当我尝试在我的控制器中返回此列表时,我得到了"不能懒惰加载json"所以我设置我的对象急切地获取.这是我的控制器

@Autowired
private MenuDaoImpl ms;

@RequestMapping(value = "/{vendorId}", method = RequestMethod.GET)
public @ResponseBody List<Product> getMenu(@PathVariable int vendorId){

    List<Product> Menu = Collections.unmodifiableList(ms.getMenuForVendor(vendorId));
    return Menu;
}
Run Code Online (Sandbox Code Playgroud)

现在,当我点击我的网址localhost:8080/getMenu/1我应该显示一个json字符串,但我得到一个很大的错误列表

WARN : org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver -       Handling of [org.springframework.http.converter.HttpMessageNotWritableException] resulted in Exception
  java.lang.IllegalStateException: Cannot call sendError() after the response has been     committed
at org.apache.catalina.connector.ResponseFacade.sendError(ResponseFacade.java:467)
 Could not write JSON: Infinite recursion (StackOverflowError) (through reference chain:
Run Code Online (Sandbox Code Playgroud)

我不确定我是否遗漏了任何东西.请指导.

Nik*_*hil 12

我使用@JsonBackReference解决了@ManyToOne绑定和@OneToMany绑定的@JsonManagedReference.

谢谢"Sotirios Delimanolis"