Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7805297
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T02:10:50+00:00 2026-06-02T02:10:50+00:00

I am using Hibernate as the ORM for a database that has a number

  • 0

I am using Hibernate as the ORM for a database that has a number of foreign key relationships. The problem is that sometimes I want to fetch these related datasets and sometimes I do not, so on these collections I have set “fetch” to “lazy”. Unfortunately, every time I try to serialize these objects Hibernate will throw a LazyInitializationException, because the session is closed. Using an OpenSessionInView filter simply causes Hibernate to populate these collections anyway, thus defeating the whole purpose of having a lazy collection in the first place.

Is there a simple way to serialize or otherwise extract the data populated in the POJO without triggering the LIE, and without having to populate all of the lazy collections?

EDIT: Here is some example code I am trying to get working, dealing with two tables, “Departments” and “Employees,” which is the child in a one-to-many relationship with Departments. I want to be able to view the Departments listed in the database, without having to load all of the Employees that belong to said Departments:

Departments:

package com.test.model;
// Generated Apr 7, 2012 7:10:28 PM by Hibernate Tools 3.4.0.CR1

import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

/**
 * Departments generated by hbm2java
 */
@Entity
@Table(name="Departments"
    ,catalog="test"
)
public class Departments  implements java.io.Serializable {


     private Integer id;
     private String name;
     private Set<Employees> employeeses = new HashSet(0);

    public Departments() {
    }


    public Departments(String name) {
        this.name = name;
    }
    public Departments(String name, Set employeeses) {
       this.name = name;
       this.employeeses = employeeses;
    }

     @Id @GeneratedValue(strategy=IDENTITY)


    @Column(name="Id", unique=true, nullable=false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }


    @Column(name="Name", nullable=false)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(fetch=FetchType.LAZY, mappedBy="departments")
    public Set<Employees> getEmployeeses() {
        return this.employeeses;
    }

    public void setEmployeeses(Set employeeses) {
        this.employeeses = employeeses;
    }
}

Employees:

package com.test.model;
// Generated Apr 7, 2012 7:10:28 PM by Hibernate Tools 3.4.0.CR1


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

/**
 * Employees generated by hbm2java
 */
@Entity
@Table(name="Employees"
    ,catalog="test"
)
public class Employees  implements java.io.Serializable {


     private Integer id;
     private Departments departments;
     private String firstName;
     private String lastName;

    public Employees() {
    }

    public Employees(Departments departments, String firstName, String lastName) {
       this.departments = departments;
       this.firstName = firstName;
       this.lastName = lastName;
    }

     @Id @GeneratedValue(strategy=IDENTITY)


    @Column(name="Id", unique=true, nullable=false)
    public Integer getId() {
        return this.id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="DepartmentsId", nullable=false)
    public Departments getDepartments() {
        return this.departments;
    }

    public void setDepartments(Departments departments) {
        this.departments = departments;
    }


    @Column(name="FirstName", nullable=false)
    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }


    @Column(name="LastName", nullable=false)
    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

My action class (which gets serialized by the Struts2 XSLT result):

package com.test.view;

import java.util.List;

import java.util.Iterator;

import com.opensymphony.xwork2.ActionSupport;
import com.test.controller.DepartmentsManager;
import com.test.model.Departments;
import com.test.util.HibernateUtil;

public class DepartmentsAction extends ActionSupport {
private DepartmentsManager departmentsManager;
private List<Departments> departmentsList;

public DepartmentsAction() {
    this.departmentsManager = new DepartmentsManager();
}

public String list() {
    this.departmentsList = departmentsManager.list();
    System.out.println("Execute called");
    HibernateUtil.createDTO(departmentsList);
    return SUCCESS;
}

public List<Departments> getDepartmentsList() {
    return departmentsList;
}

public void setDepartmentsList(List<Departments> departmentsList) {
    this.departmentsList = departmentsList;
}
}

My Manager class (which the Action class calls to populate the list of Departments):

package com.test.controller;

import java.util.List;

import java.util.Iterator;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import com.test.model.Departments;
import com.test.util.HibernateUtil;

public class DepartmentsManager {
public List<Departments> list() {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    List<Departments> set = null;
    try {
        Query q = session.createQuery("FROM Departments");
        /*Query q = session.createQuery("FROM Departments d JOIN FETCH d.employeeses e");*/
        q.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
        set = (List<Departments>) q.list();
    } catch (HibernateException e) {
        e.printStackTrace();
        session.getTransaction().rollback();
    }
    session.getTransaction().commit();
    return set;
}
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-02T02:10:52+00:00Added an answer on June 2, 2026 at 2:10 am

    Lazy collections work only within the scope of the transaction (where the owning entity was retrieved from a DB). In other words, you should not pass a Hibernate entity with non-loaded lazy sub-entities or collections outside the transaction scope.

    You need either to build another entity or use lazy=”false” if you want to pass an entity to JSP, or serialization code or anything else.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm using Hibernate for ORM of my Java app to an Oracle database (not
I'm using Coldfusion ORM (Hibernate), and have a cfc mapped to a database table.
I'm just starting to learn Java database persistence using Hibernate ORM and have run
I am using hibernate as ORM tool, i want to perform some common stuff
Today I was trying to create a application using Hibernate as ORM. So while
We are developing a web application using Spring framework and Hibernate ORM. As far
Am I right that using NHibernate (or any other ORM) removes the necessity of
In my application, Spring manages connection pool for database access. Hibernate uses these connections
Assume Hibernate for the ORM. I'm not sure how to ask this. I want
We have a Hibernate/Spring application that have the following Spring beans: <bean id=transactionManager class=org.springframework.orm.hibernate3.HibernateTransactionManager

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.