我有兩個類:Spring:爲什麼normal和@ResponseBody控制器生成不同的代碼?
/* ------------------------------------------------------ */
@Entity
@Table(name="ABC")
@NamedQuery(name="Abc.findAll", query="SELECT c FROM Abc c")
public class Abc implements Serializable {
@Id @Column(unique=true, nullable=false)
private int id;
@ManyToOne
@JoinColumn(name="def_id", nullable=false)
private Def def;
// getters and setters...
}
/* ------------------------------------------------------ */
@Entity
@Table(name = "DEF")
@NamedQuery(name = "Def.findAll", query = "SELECT c FROM Def c")
public class Def implements Serializable {
@Id @Column(unique = true, nullable = false)
private int id;
@OneToMany(mappedBy = "def")
private List<Abc> abc;
public Def() {
}
// getters and setters...
}
/* ------------------------------------------------------ */
Abc
有Def
多對一關聯。
我需要從類Abc
生成HTML表和JSON。我在控制器下面的代碼:
@RequestMapping(value="/page", method=RequestMethod.GET) // HTML table
public String getPage(Model model) {
List<Abc> abc = AbcManager.findAll();
model.addAttribute("abc", abc);
return "abc";
}
@RequestMapping(value="/json", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE) // JSON (REST API)
public @ResponseBody List<Abc> getJson() {
List<Abc> abc = AbcManager.findAll();
return abc;
}
如果我去的URL /page
,一切正常。但如果我去url /json
我得到這個錯誤:
Oct 11, 2014 11:01:19 ODP. org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [spring] in context with path [/project] threw exception [Request processing failed; nested exception is org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: net.example.project.entity.Def.nodes, could not initialize proxy - no Session] with root cause
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: net.example.project.entity.Def.nodes, could not initialize proxy - no Session
問題在哪裏?我不希望在輸出中包含所有Def
的列表。 「正常」控制器對我來說是正確的,但不是其他控制器。爲什麼?
我該如何解決?