gpt4 book ai didi

java - 使用 JSONArray.fromObject 将 Hibernate 实体转换为 json

转载 作者:行者123 更新时间:2023-11-30 05:58:00 25 4
gpt4 key购买 nike

我在将数据转换为 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...

}

谢谢

最佳答案

您的 employees 集合被标记为 FetchType.LAZY,因此它是延迟获取的,并且在 session 关闭时无法获取。

您有多种选择:

  • 如果每次加载 Affiliate 对象时都需要该集合,请将其标记为急切获取:

    @ManyToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER) 
  • 如果您仅在这种特殊情况下需要该集合,请指示 Hibernate 在这种情况下立即加载它:

    • 使用 JOIN FETCH 子句:

      Affiliate affiliate = (Affiliate) session.createQuery(
      "from Affiliate a join fetch a.employees where a.id = :id")
      .setParameter("id", pk).uniqueResult()
    • 使用Hibernate.initialize():

      Affiliate affiliate = (Affiliate) session.get( Affiliate , pk );  
      Hibernate.initialize(affiliate.getEmployees());
    • Fetch Profiles

  • 在响应准备好之前不要关闭 session 。使用Open Session in View模式。

关于java - 使用 JSONArray.fromObject 将 Hibernate 实体转换为 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4874879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com