Struts + Hibernate LazyInitializationException错误

时间:2016-02-28 08:51:43

标签: hibernate

在我的User类中,我有4个属性,分别包含getter和setter。

package com.model;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

@Entity(name="Users")
public class Users {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="UserID")
    private int userID;

    @Column(length=25,name="IDNo")
    private String idNo;

    @Column(length=25,name="FirstName")
    private String firstName;

    @Column(length=25,name="LastName")
    private String lastName;

    @Column(length=25,name="UserName")
    private String username;

    @Column(name="PictureUrl",insertable=false, updatable = true, nullable = false,
    columnDefinition="varchar(250) default 'resources/img/avatar.png'")
    private String pictureUrl;


    @OneToMany(mappedBy="users", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<AccountType> accountType;

    @OneToMany(mappedBy="users", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Password> password;

    @OneToMany(mappedBy="users", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<ProfessorProfile> professorProfile;

    @OneToMany(mappedBy="users", cascade=CascadeType.ALL, fetch = FetchType.LAZY)
    private Set<Classlist> ClassList;

    public Set<Classlist> getClassList() {
        return ClassList;
    }
    public void setClassList(Set<Classlist> ClassList) {
        this.ClassList = ClassList;
    }
    public Set<ProfessorProfile> getProfessorProfile() {
        return professorProfile;
    }
    public void setProfessorProfile(Set<ProfessorProfile> professorProfile) {
        this.professorProfile = professorProfile;
    }
    public Set<Password> getPassword() {
        return password;
    }
    public void setPassword(Set<Password> password) {
        this.password = password;
    }
    public Set<AccountType> getAccountType() {
        return accountType;
    }
    public void setAccountType(Set<AccountType> accountType) {
        this.accountType = accountType;
    }
    public int getUserID() {
        return userID;
    }
    public void setUserID(int userID) {
        this.userID = userID;
    }
    public String getIdNo() {
        return idNo;
    }
    public void setIdNo(String idNo) {
        this.idNo = idNo;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPictureUrl() {
        return pictureUrl;
    }
    public void setPictureUrl(String pictureUrl) {
        this.pictureUrl = pictureUrl;
    }


    public Users(){}

    public Users(String idNo,String firstName,String lastName,String userName){
        setIdNo(idNo);
        setFirstName(firstName);
        setLastName(lastName);
        setUsername(userName);
    }
    public Users(String idNo,String firstName,String lastName){
        setIdNo(idNo);
        setFirstName(firstName);
        setLastName(lastName);
    }
    public Users(String pictureUrl,int id){
        setPictureUrl(pictureUrl);
        setUserID(id);
    }

    public Users(String username){
        setUsername(username);
    }


}

在我的Hibernate中

    public Set<Users> viewAllProfessors(){

        Session session = null;
        Transaction trans = null;
        Set<Users> list = new HashSet<Users>();

        try {
            session = HibernateFactory.getSession().openSession();
            trans = session.beginTransaction();
            Query query = session.createQuery("SELECT u from Users u join fetch u.accountType");

            for(Object o : query.list()){
                list.add( (Users) o );
            }

            trans.commit();

        } catch (Exception e) {
            // TODO: handle exception
            if(trans != null){
                trans.rollback();
            }
        } finally{
            session.close();
        }

        return list;
    }

Struts行动

package com.action.developer;

import java.util.HashSet;
import java.util.Set;

import com.HibernateUtil.DeveloperHelper;
import com.model.Users;
import com.opensymphony.xwork2.ActionSupport;

public class DeveloperViewProfessors extends ActionSupport {

private Set<Users> users = new HashSet<Users>();

@Override
public String execute() throws Exception {
    // TODO Auto-generated method stub
    DeveloperHelper session_Helper = new DeveloperHelper();
    users = session_Helper.viewAllProfessors();



    return SUCCESS;
}

public Set<Users> getUsers() {
    return users;
}
public void setUsers(Set<Users> users) {
    this.users = users;
}

}

我知道当您尝试在打开的会话外访问集合时会发生LazyInitializationException。我尝试了Session-View模式,你将在其中重新打开会话但它仍然调用其他属性..我只想查询用户和AccountType实体。我不需要classlistprofessorProfilepassword属性。

我也尝试过Hibernate.Initialize(),但它要求我初始化所有属性(classlistpasswordprofessorProfile及其子集合!)

顺便说一句,我正在通过ajax将数据从hibernate传递给struts到angularjs作为Json。有问题吗?我正在使用Struts2 json插件

2 个答案:

答案 0 :(得分:0)

我前段时间有过类似的问题,要解决此问题,您应该使用hibernate.enable_lazy_load_no_trans property而不是Open Session-View模式。有关LazyInitializationException的更多信息:Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans

<property name="hibernate.enable_lazy_load_no_trans" value="true"/>

答案 1 :(得分:0)

我终于解决了Hibernate + Struts w / json的着名懒惰初始化异常错误!在Hibernate.initialize()关闭之前,我在所需的属性上使用了session。在我的例子中是accountType属性。最重要的是,如果您使用带有struts的json,则必须在struts.xml中排除属性。

public Set<Users> viewAllProfessors(){

    Session session = null;
    Transaction trans = null;
    Set<Users> list = new HashSet<Users>();

    try {
        session = HibernateFactory.getSession().openSession();
        trans = session.beginTransaction();
        Query query = session.createQuery("from Users");

        list = query.list();
        list.forEach(i -> {
          Hibernate.initialize(i.getAccountType());
        });
        trans.commit();

    } catch (Exception e) {
        // TODO: handle exception
        if(trans != null){
            trans.rollback();
        }
    } finally{
        session.close();
    }

    return list;
}

XML

<action name="viewProfessors" class="com.action.developer.DeveloperViewProfessors">
        <interceptor-ref name="myStack"/>
        <result name="success" type="json">
            <param name="excludeNullProperties">true</param>
            <param name="excludeProperties">
                users\[\d+\]\.classList,
                users\[\d+\]\.professorProfile,
                users\[\d+\]\.password
            </param>
        </result>
    </action>