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

  • Home
  • SEARCH
  • 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 7971797
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T07:42:45+00:00 2026-06-04T07:42:45+00:00

Lets say in an application you have an entity called User. Each User can

  • 0

Lets say in an application you have an entity called User. Each User can have many Articles which are loaded using lazy fetching.

@Entity
@Table(name = "Users")
public class User {
  private Integer id;
  private Set<Article> articles = new HashSet<Article>();

  ...

  @OneToMany(fetch = FetchType.LAZY, mappedBy = "user", cascade = CascadeType.ALL)
  public Set<Article> getArticles() {...}
}

On the web service end, I want to load a user by Id and pass it to a jersey Viewable JSP to be returned and displayed. I also want to use a single session for every request.

@GET
public Response getUser() {
  Session session = getSessionFactory().openSession();
  session.beginTransaction();

  User user = (User) session.getNamedQuery("getUserById").setInteger("id", 1).uniqueResult();
  Map<String, Object> dataMap = new HashMap<String, Object>();
  dataMap.put("user", user);
  Viewable v = new Viewable("/user", dataMap);
  Response r = Response.ok(v).build();

  session.getTransaction().commit();
  session.close();
  return r;
}

In user.jsp, I want to access the articles and print them out.

<c:forEach var="a" items="${it.user.articles}">
  <span>${a.title}</span>
</c:forEach>

Running this code and trying to request the JSP ends up throwing an exception:

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: my.package.User.articles, no session or session was closed

This happens because apparently creating the Viewable, passing it to the ResponseBuilder and calling build() doesn’t actually create the JSP. The JSP is created somewhere further down the line, after my method has returned and the session has been closed.

One obvious option would be to set the fetch type for articles to eager, but that’s not ideal as in most cases I will not need to load or display the articles when I’m using a User object.

Is there a way to force jersey to interpret and construct the jsp before my method returns? Is there some kind of onResponse or postResponse listener I could pass my code to close the session to?

Is there anything I should be doing differently with the way I’m handling opening/closing hibernate sessions in general? From googling around, one-session-per-request seems to be what most people advocate using so I thought I’d try that.

  • 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-04T07:42:46+00:00Added an answer on June 4, 2026 at 7:42 am

    The “open session in view” approach is indeed the way to solve this problem.

    Another way is to use EJB or Spring. They will then take over the transaction handling. EJB does it fully transparently when using with JPA EntityManager and Spring provides the org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter filter for this.

    If your container supports EJB, then just create a @Stateless:

    @Stateless
    public class UserService {
    
        @PersistenceContext
        private EntityManager em;
    
        public User find(Integer id) {
            return em.createNamedQuery("getUserById", User.class)
                .setParameter("id", id)
                .getSingleResult();
        }
    
    }
    

    and use it in your web service as follows:

    @EJB
    private UserService userService;
    
    @GET
    public Response getUser() {
        User user = userService.find(1);
    
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("user", user);
        Viewable v = new Viewable("/user", dataMap);
        Response r = Response.ok(v).build();
        return r;
    }
    

    No need to worry about transactions and lazy fetching anymore.

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

Sidebar

Related Questions

Lets say i have an application which has three text-fields, and i can type
Lets say we have a application which has a database - MySQL, SQL Server,
Kinda stuck here... I have an application with lets say 5000 rows of data
I have icons inside my application for uibutton & on uitable cell. Lets say
I have an application which creates objects of a certain kind (let's say, of
Let's say I have an User entity and I would want to set it's
Lets say you have an application. This application is to be QA tested and
Lets say I have an application that is going to listen on a particular
Let's say I have 'Customer' table in SQL DB and I'm using Entity Framework.
Lets say i have an application ( the details of the application should be

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.