0

In my User class I have this 4 properties with getters and setters respectively.

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


}

In my 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 action

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;
}

}

I know that LazyInitializationException occurs when you are trying to access the collection outside the opened session. I tried the Session-View pattern in which you would REMAIN open the session but it still calls the other properties.. I just want to query the Users and AccountType entities. I don't need the classlist, professorProfile and password properties.

I also tried to do the Hibernate.Initialize(), but it requires me to initialize all the properties (classlist, password, professorProfile and their child-collections too!)

Btw, i'm passing the data from hibernate to struts to angularjs as Json by ajax. Does it have problem? I'm using Struts2 json plugin with this

Aleksandr M
  • 23,647
  • 12
  • 63
  • 129
Jm Santos
  • 21
  • 1
  • 4

2 Answers2

0

I've had similar question some time ago, to resolve this you should use hibernate.enable_lazy_load_no_trans property instead of Open Session-View pattern. More information about LazyInitializationException: Solve Hibernate Lazy-Init issue with hibernate.enable_lazy_load_no_trans.

<property name="hibernate.enable_lazy_load_no_trans" value="true"/>
Community
  • 1
  • 1
Roman C
  • 47,329
  • 33
  • 60
  • 147
0

I finally solved the famous lazy initialization exception error of Hibernate + Struts w/ json! I used the Hibernate.initialize() on the properties that I want before the session is closed. Which in my case is the accountType property. And most importantly you MUST EXCLUDE PROPERTIES in the struts.xml if you're using json with struts.

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>
Jm Santos
  • 21
  • 1
  • 4