Raki
Raki

Reputation: 1

Could not write content: could not initialize proxy - no Session

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

I get these error log when viewing a page

Etat HTTP 500 - Could not write content: failed to lazily initialize a collection of role: org.service.pf.entities.Categorie.souscategorie, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->org.service.pf.entities.Souscategorie["categorie"]->org.service.pf.entities.Categorie["souscategorie"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: org.service.pf.entities.Categorie.souscategorie, could not initialize proxy - no Session (through reference chain: 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 !

Upvotes: 0

Views: 4307

Answers (2)

STK
STK

Reputation: 167

You can set FetchType.LAZY on your entity columns and retrieve the object without pulling the associated objects. Here is how I did,

I am using Spring MVC 4, Hibernate 4, Spring Rest

Problem Statement

I wanted to get the Answer_tbl Entity object from the database but I get the exception

Could not write content: could not initialize proxy - no Session through reference chain

My Answer Entity Class

@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

When I called the service http://localhost:8080/myapp/rest/answer/2, got the same exception as yours.

The problem is actually FetchType.lazy. Jackson attempts to converts the Answer_tbl Entity, it trys to load the associated objects ( Question_tbl & Shaikh_tbl ) but the hibernate session is closed.

Solution

One solution is to remove the fetch = FetchType.LAZY, then hibernate will load the associations eagerly. But its not what you are looking for.

The second solution is use the Jackson JSON processor which could handle lazy-loading functionality.

Here are the steps

Add the following Maven dependency

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

Register the module with ObjectMapper

public class HibernateAwareObjectMapper extends ObjectMapper {

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

}

Add the following code in your 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> 

Now when I called the service http://localhost:8080/myapp/rest/answer/2, I get the following JSON. No association retrieved, only Answer_tbl object is available.

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

Here is the Git link FasterXML-Jackson-Datatype-Hibernate

Hope this would be helpful.

Upvotes: 3

Stan
Stan

Reputation: 1430

You are trying to access collection out of Hibernate's session. Try to define your relation as

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

so data will be loaded one you are loading parent entity

Upvotes: 0

Related Questions