我在將數據轉換爲json時遇到問題。使用JSONArray.fromObject將Hibernate實體轉換爲json
Session session = sessionFactory.openSession();
Affiliate affiliate = (affiliate) session.get(Affiliate , pk);
session.close();
JSONArray.fromObject(affiliate);
調試器顯示行被提取。
,但我得到試圖轉換到JSON字符串時,此異常:
Exception in thread "main" net.sf.json.JSONException: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.affiliates.hibernate.Affiliate.employees, no session or session was closed
at net.sf.json.JSONObject._fromBean(JSONObject.java:959) ...
這是我加盟實體
@Entity(name="AFFILIATE")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Affiliate extends HibernateBean{
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="AFFILIATE_ID")
private long id;
@ManyToOne(targetEntity = Affiliate.class)
@JoinColumn(name="PARENT_ID")
private Affiliate parent;
@ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.LAZY)
@JoinTable(name="EMPLOYEES_AFFILIATES" , joinColumns = {@JoinColumn(name="AFFILIATE_ID")},inverseJoinColumns={@JoinColumn(name="EMPLOYEE_ID")})
private Set<Employee> employees = new HashSet<Employee>(0);
getters and setters...
}
感謝
謝謝,我不明白一件事,取懶意味着emplyees將是空的,不是? ...因爲如果我正在寫affiliate.setEmployees(null),它工作正常。這是我理解提取懶惰假設要做的,將emplyees設置爲null。 – fatnjazzy 2011-02-02 14:15:04