Spring,Hibernate:多对多映射的惰性初始化异常 [英] Spring, Hibernate : Lazy initialization exception for many-to-many mapping

查看:126
本文介绍了Spring,Hibernate:多对多映射的惰性初始化异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个Spring-MVC应用程序,其中我试图为两个实体之间已经存在的一对多映射添加多对多映射。我们在项目中拥有两个实体 GroupSection GroupNotes



对于项目中的任务之一,我必须在GroupSection和GroupNotes之间引入一个多对多的映射,但是我得到了一个懒惰的初始化异常。 p>

错误:

  org.springframework.http.converter.HttpMessageNotWritableException:可能不写内容:无法懒惰地初始化一个角色集合:com.tooltank.spring.model.GroupSection.groupSections,无法初始化代理 - 没有会话(通过引用链:java.util.ArrayList [0]  - > com。 tooltank.spring.model.GroupSection [ groupSections]);嵌套的异常是com.fasterxml.jackson.databind.JsonMappingException:未能懒惰地初始化一个角色集合:com.tooltank.spring.model.GroupSection.groupSections,无法初始化代理 - 没有会话(通过引用链:java.util。 ArrayList [0]  - > com.tooltank.spring.model.GroupSection [groupSections])

以下是调用的控制器方法:

  @RequestMapping(value =/ sections / get / {canvasid}) 
public @ResponseBody List< GroupSection> getAllSectionsForCanvas(@PathVariable(canvasid)int canvasid){
布尔值= this.personService.getCanvasValuesForCanvas(canvasid);
返回this.groupSectionService.listGroupSectionByCanvasid(canvasid,value);

$ / code>

DAO方法(Service方法只是调用DAO方法):

  @Override 
@Transactional(readOnly = true)
public List< GroupSection> listGroupSectionByCanvasid(int mcanvasid){
try {
Session session = this.sessionFactory.getCurrentSession();
org.hibernate.Query query = session.createQuery(From GroupSection as msection where+
msection.currentcanvas.mcanvasid =:mcanvasid and msection.sectionDisabled = false and msection.sectionInActive = false) ;
query.setParameter(mcanvasid,mcanvasid);
返回query.list();
} catch(Exception e){
e.printStackTrace();
返回null;


GroupSection模型:

  import com.fasterxml.jackson.annotation.JsonIgnore; 
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

import javax.persistence。*;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Entity
@Table(name =membersection)
public class GroupSection {


//下面是自我映射,需要一个的任务,工作。
@JsonIgnore
@ManyToOne
@JoinColumn(name =owned_section_id,nullable = true)
私有GroupSection primarySection;

@OneToMany(mappedBy =primarySection,fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
private Set< GroupSection> groupSections = new HashSet<>();


//多对多的映射,我之前有懒加载,但试过急于看看错误是否会发生,但事实并非如此。 :

@ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
@JoinTable(name =sectionjunction,joinColumns = {@JoinColumn(name =msectionid)} ,
inverseJoinColumns = {@JoinColumn(name =mnoteid)})
private Set< GroupNotes> groupNotesSet = new HashSet<>();


//一对多映射如下:

@OneToMany(mappedBy =ownednotes,fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
@JsonIgnore
私人套餐< GroupNotes> sectionsnotes = new HashSet<>();
}

GroupNotes:

  import com.fasterxml.jackson.annotation.JsonIgnore; 
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

import javax.persistence。*;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Entity
@Table(name =groupnotes)
public class GroupNotes implements Serializable {


@JsonIgnore
@ManyToMany( mappedBy =groupNotesSet,fetch = FetchType.EAGER)
private Set< GroupSection> groupSectionSet = new HashSet<>();

@ManyToOne
@JoinColumn(name =msectionid,nullable = true)
@JsonIgnore
Private GroupSection ownednotes;

//自映射:


@JsonIgnore
@ManyToOne
@JoinColumn(name =owned_note_id,nullable = true)
私人GroupNotes primaryNote;

@OneToMany(mappedBy =primaryNote,fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
private Set< GroupNotes> groupNotesSet = new HashSet<>();
}

我做错了什么?是否有可能同时在两个类之间进行一对多和多对多映射?如果是的话,那么该错误的处理是什么。请让我知道。谢谢。 : - )

解决方案

当调用listGroupSectionByCanvasid时,你打开一个事务和一个会话。当呼叫返回会话关闭时。当spring返回它试图读取你的对象的值,并且由于你的manytomany关系组的延迟加载groupNotesSet和groupSections是需要会话的hibernate集合。在你的情况下,会话不再存在。


I am working on a Spring-MVC application in which I am trying to add many-to-many mapping for an already existing one-to-many mapping between two entities. Two entities which we have in the project are GroupSection and GroupNotes.

For one of the task in project, I had to introduce a many-to-many mapping between GroupSection and GroupNotes, but I am getting a lazy initialization exception.

Error :

org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: failed to lazily initialize a collection of role: com.tooltank.spring.model.GroupSection.groupSections, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.tooltank.spring.model.GroupSection["groupSections"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: failed to lazily initialize a collection of role: com.tooltank.spring.model.GroupSection.groupSections, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->com.tooltank.spring.model.GroupSection["groupSections"])

Here is the controller method which was called:

@RequestMapping(value = "/sections/get/{canvasid}")
    public @ResponseBody List<GroupSection> getAllSectionsForCanvas(@PathVariable("canvasid") int canvasid) {
        boolean value = this.personService.getCanvasValuesForCanvas(canvasid);
        return this.groupSectionService.listGroupSectionByCanvasid(canvasid, value);
    }

DAO method(Service method just calls the DAO method) :

   @Override
    @Transactional(readOnly = true)
    public List<GroupSection> listGroupSectionByCanvasid(int mcanvasid) {
        try {
            Session session = this.sessionFactory.getCurrentSession();
            org.hibernate.Query query = session.createQuery("From GroupSection as msection where " +
                    "msection.currentcanvas.mcanvasid=:mcanvasid and msection.sectionDisabled=false and msection.sectionInActive=false");
            query.setParameter("mcanvasid", mcanvasid);
            return query.list();
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }

GroupSection model :

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Entity
@Table(name = "membersection")
public class GroupSection {


// Below is self-mapping, required for one of the task, works.
    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "owned_section_id", nullable = true)
    private GroupSection primarySection;

    @OneToMany(mappedBy = "primarySection", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
    private Set<GroupSection> groupSections = new HashSet<>();


// Many to many mapping, I had lazy loading before, but tried Eager to see if error goes, it doesn't. :

    @ManyToMany(fetch = FetchType.LAZY,cascade = CascadeType.REMOVE)
    @JoinTable(name = "sectionjunction",joinColumns = {@JoinColumn(name = "msectionid")},
            inverseJoinColumns = {@JoinColumn(name = "mnoteid")})
    private Set<GroupNotes> groupNotesSet = new HashSet<>();


// One to many mapping below :

@OneToMany(mappedBy = "ownednotes", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
@JsonIgnore
private Set<GroupNotes> sectionsnotes = new HashSet<>();
}

GroupNotes :

import com.fasterxml.jackson.annotation.JsonIgnore;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;

import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Entity
@Table(name = "groupnotes")
public class GroupNotes implements Serializable {


    @JsonIgnore
    @ManyToMany(mappedBy = "groupNotesSet",fetch = FetchType.EAGER)
    private Set<GroupSection> groupSectionSet = new HashSet<>();

    @ManyToOne
    @JoinColumn(name = "msectionid",nullable = true)
    @JsonIgnore
    private GroupSection ownednotes;

 // Self mappings :


    @JsonIgnore
    @ManyToOne
    @JoinColumn(name = "owned_note_id", nullable = true)
    private GroupNotes primaryNote;

    @OneToMany(mappedBy = "primaryNote", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
    private Set<GroupNotes> groupNotesSet = new HashSet<>();
}

What am I doing wrong? Is it possible to simultaneously have one-to-many and many-to-many mapping between 2 classes. If yes, then what's the deal with that error. Kindly let me know. THank you. :-)

解决方案

When calling listGroupSectionByCanvasid you open a transaction and a session. When the call return the session is closed. And when spring is returning the value it tries to read you object and because of lazy loading of your manytomany relation groupNotesSet and groupSections are hibernate collections that need the session. And in your case session doesn't exsit anymore.

这篇关于Spring,Hibernate:多对多映射的惰性初始化异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆