无法写内容:无法初始化代理 - 没有会话

时间:2016-05-30 14:20:49

标签: hibernate spring-mvc jpa

  //i use ajax, spring mvc , hibernate-jpa

我在查看页面时收到这些错误日志

Etat HTTP 500 - 无法写入内容:懒得初始化角色集合:org.service.pf.entities.Categorie.souscategorie,无法初始化代理 - 无会话(通过引用链:java.util.ArrayList [0] - > org.service.pf.entities.Souscategorie [ “categorie”] - > org.service.pf.entities.Categorie [ “souscategorie”]);嵌套异常是com.fasterxml.jackson.databind.JsonMappingException:懒得初始化一个角色集合:org.service.pf.entities.Categorie.souscategorie,无法初始化代理 - 没有Session(通过引用链:java.util。 ArrayList的[0] - > org.service.pf.entities.Souscategorie [ “categorie”] - > org.service.pf.entities.Categorie [ “souscategorie”])

//my controller 

     @RequestMapping(value="/filtrecatgajax")
     @ResponseBody 
    public List<Souscategorie> getAllProductByKategori(@RequestParam(value = "id", required = true) String id  ){

    return metiersr.SouscategoriesParCategorie((long) Integer.parseInt(id)); 
}

 //My dao function 

 public class ServicedaoImpl implements Servicedao {
 @PersistenceContext

  @Override
   public List<Souscategorie> SouscategoriesParCategorie(Long idCat) {
    Query query = em
            .createQuery("SELECT p FROM Souscategorie p WHERE   p.categorie.id=:x");
    query.setParameter("x", idCat);
    return query.getResultList();

}
}

//Relation OneToMany

        @OneToMany(mappedBy = "categorie")
        private Collection<Souscategorie> souscategorie;

//Relation ManyToOne

        @ManyToOne
        @JoinColumn(name = "categorie_id")
        private  Categorie categorie;

   Can someone help me !

2 个答案:

答案 0 :(得分:2)

您可以在实体列上设置FetchType.LAZY并检索对象而不拉动关联的对象。我是这样做的,

我正在使用Spring MVC 4,Hibernate 4,Spring Rest

问题陈述

我想从数据库中获取Answer_tbl Entity对象,但是我得到了异常

  

无法写内容:无法初始化代理 - 无会话   通过参考链

我的答案实体类

@Entity
@Table(name = "Answer")
public class Answer_tbl implements Serializable {

    @Id
    @Column(name = "AnswerId")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name="QuestionId")
    private Question_tbl question;

    @ManyToOne(optional = false, fetch = FetchType.LAZY)
    @JoinColumn(name="ShaikhId")
    private Shaikh_tbl shaikh; 

    // getters and setters

当我拨打服务http://localhost:8080/myapp/rest/answer/2时,得到了与您相同的例外情况。

问题实际上是FetchType.lazy。 Jackson尝试转换Answer_tbl实体,它试图加载相关对象(Question_tbl&amp; Shaikh_tbl),但是休眠会话已关闭。

解决方案

一种解决方案是删除fetch = FetchType.LAZY,然后hibernate会急切地加载关联。但它不是你想要的。

第二个解决方案是使用可以处理延迟加载功能的Jackson JSON处理器。

以下是步骤

添加以下Maven依赖

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-hibernate4</artifactId>
  <version>2.5.3</version>
</dependency>  

使用ObjectMapper注册模块

public class HibernateAwareObjectMapper extends ObjectMapper {

    public HibernateAwareObjectMapper() {
        registerModule(new Hibernate4Module());
    }

}

在Spring XML Config中添加以下代码

<mvc:annotation-driven>
    <mvc:message-converters>
        <!-- Use the HibernateAware mapper instead of the default -->
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="path.to.your.HibernateAwareObjectMapper" />
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven> 

现在,当我调用服务http://localhost:8080/myapp/rest/answer/2时,我得到以下JSON。没有检索到关联,只有Answer_tbl对象可用。

{
  "id": 2,
  "question": null,
  "shaikh": null,
  "solution": "testing...",
}

以下是Git链接FasterXML-Jackson-Datatype-Hibernate

希望这会有所帮助。

答案 1 :(得分:0)

您正在尝试从Hibernate会话中访问集合。尝试将您的关系定义为

@OneToMany(mappedBy = "categorie", fetch = FetchType.EAGER)

因此,您正在加载父实体

时将加载数据