Spring,Hibernate:多对多映射的惰性初始化异常

时间:2016-03-03 08:58:55

标签: java spring hibernate spring-mvc

我正在开发一个Spring-MVC应用程序,我正在尝试为两个实体之间已存在的一对多映射添加多对多映射。我们在项目中拥有的两个实体是GroupSectionGroupNotes

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

错误:

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"])

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

@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方法(服务方法只调用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);
            return query.list();
        }catch (Exception e){
            e.printStackTrace();
            return 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 {


// 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<>();
}

我做错了什么?是否可以同时在两个类之间进行一对多和多对多映射。如果是,那么该错误的处理方式是什么。请告诉我。谢谢。 : - )

1 个答案:

答案 0 :(得分:0)

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

相关问题