The content could not be created due to an inability to lazily initialize a collection of roles. The proxy could not be initialized as there was no

Encountering an error with FetchType.LAZY:

Error message: failed to lazily initialize a collection of role: com.websystique.springmvc.model.User.userProfiles, could not initialize proxy - no Session

Here is the model class in question:

@SuppressWarnings("serial")
@Entity
@Table(name="APP_USER")
public class User implements Serializable{

    @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

    @NotEmpty
    @Column(name="SSO_ID", unique=true, nullable=false)
    private String ssoId;

    @NotEmpty
    @Column(name="PASSWORD", nullable=false)
    private String password;

    @NotEmpty
    @Column(name="FIRST_NAME", nullable=false)
    private String firstName;

    @NotEmpty
    @Column(name="LAST_NAME", nullable=false)
    private String lastName;

    @NotEmpty
    @Column(name="EMAIL", nullable=false)
    private String email;

    @NotEmpty
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(name = "APP_USER_USER_PROFILE", 
             joinColumns = { @JoinColumn(name = "USER_ID") }, 
             inverseJoinColumns = { @JoinColumn(name = "USER_PROFILE_ID") })
    private Set<UserProfile> userProfiles = new HashSet<UserProfile>();

    // getters/setters ....
 
... (remaining content unchanged) // Controller and service classes remain unchanged.

However, after making a change to FetchType.EAGER, the issue gets resolved. Despite this, I'd like to stick with LAZY for memory utilization benefits.

Is there a way to make the ajax call work with LAZY? Any guidance would be highly appreciated.

========================================================================= UPDATE

UserDaoImpl class snippet:

@Repository("userDao")
public class UserDaoImpl extends AbstractDao<Integer, User> implements UserDao {
    ...

    public List<User> findAllUsers() {
        ...
        // Code for fetching user profiles eagerly commented out.
        return users;
    }   

}
 
... (remaining content unchanged)

Upon revisiting the Dao code, I realized that I had mistakenly enabled eager fetching by uncommenting a section of code. After rectifying this and switching back to LAZY fetch type as per the model class, the ajax call worked flawlessly. Apologies for the oversight.

Despite setting the FetchType to LAZY in the model class, overriding it in the Dao somehow made the ajax call function smoothly. The intricacies behind this behavior still puzzle me.

For further information on this code, please refer to the link provided here.

Answer №1

The current setup of your application does not allow for Hibernate session to be active in the view. The session is closed after the request is processed but before the view is rendered.

When using FetchType.EAGER, all data is loaded during the request BEFORE rendering the view, resulting in the application working properly. However, with FetchType.LAZY, the data is loaded on demand - such as in the view - leading to a Hibernate exception due to the session being closed at that moment.

One solution for this issue, for example in Spring Boot configuration, is:

spring.jpa.open-in-view: true

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to retrieve the $state object from ui router in the console?

I attempted to modify the route from the console by using this method to access the $state object: $inject = angular.injector(['ng', 'ui.router']); $inject.get('$state').go Unfortunately, I encountered an error: Uncaught Er ...

Is there an h1 heading on this page?

Trying to enhance the accessibility of a website by properly setting up the headers. Running into issues with ensuring they are in the correct order. If there is code that could be applied across all pages to set h1 if it doesn't exist (promoting h2, ...

Mastering Promises, Async/Await for managing the flow of execution

Exploring the concepts of promises, await, and async functions has been a fascinating journey for me. As I delved into promises, I discovered an interesting aspect - the unpredictable order in which requests were resolved when multiple requests were sent o ...

Can ChatGPT Service Error be resolved?

I tried using chatGPT to help me with my HTML code, but every time I opened it I received an error message saying "Failed to get service" Here is the code that I want to make work: <html> <head></head> <body> <script& ...

Reverse the text alteration when the user leaves the field without confirming

Upon exiting a text box, I aim to display a confirmation dialogue inquiring whether the user is certain about making a change. If they select no, I would prefer for the text box to revert back to its original state. Is there an uncomplicated method to ach ...

How can I retrieve data using the angular method instead of the traditional $.ajax approach? Is $http a suitable replacement for $.ajax in Angular?

Here is the code snippet I have written. .state("dynamic", { url: "/:name", controller : 'AppHomeCtrl', templateUrl: function (params){ var myURL = params.name + '.html'; var validPage ...

Troubleshooting type casting issue in Typescript when working with objects containing getters and setters

I'm facing an issue with the code snippet provided. I suspect it might be related to casting, but I'm unable to pinpoint the exact solution. interface Code { code: string; expiration: number; } interface IActivationCode { [userId: string] ...

In a JavaScript array of objects, the Vuetify select :items feature allows you to assign an id and name to each object. When a name is selected, the corresponding id is automatically

I am currently working with an array of objects that contain both an id and a name property: Teams [ { id: 1, name: 'team1' }, { id:2, name: 'team2' } ] Is there a way to dynamically pass the names as items in a vuetify selec ...

Turn off all page scrolling on website

Is there a way to completely eliminate scrolling on a webpage? Currently, I have implemented the following CSS: html, body { overflow:hidden; } However, this solution does not effectively disable scrolling on iOS devices. In fact, it still allows scroll ...

Struggling with implementing Ajax live search for multiple values in PHP

I've been working on a live search feature using Ajax and PHP, and everything seems to be functioning properly. However, I've encountered a minor issue that needs addressing before I can consider it fully operational. Currently, the list only upd ...

Angular - Execute function every 30 seconds while considering the duration of the function execution

In my Angular 7 application, I am utilizing RxJS to handle asynchronous operations. My goal is to retrieve a list of items from an API endpoint every 30 seconds. However, there are times when the request may take longer than expected, and I want to ensure ...

Gulp does not work well with Android APK compilation

Greetings, I am facing an issue while trying to compile my Android app using gulp with the command: gulp --prod -p android. The problem arises when comparing the file size of the generated APK between myself and a colleague. When my colleague compiles, the ...

How can I prevent the Firefox pop-up stating "This web page is being redirected to a new location" from appearing with every requestPromise AJAX call?

My web app has extensive AJAX functionality. While initially working fine in my tests, today I encountered an issue with Firefox on both Mac and IE where a pop-up message "This web page is being redirected to a new location" appears for every PUT and DELET ...

What is the best way to access the value of an HTML tag in React?

Currently in the process of developing a feature for the price tab using React. These components are designed to allow users to add price classes to their shopping cart. One challenge I'm facing is how to retrieve the HTML string of an HTML tag. Here& ...

Resources for Vue.js stylesheets

Vue.js is my latest discovery and I have been experimenting with the single file component architecture. A small issue I encountered was that all of my components' styles were being loaded on the page, even if they weren't currently active. Is t ...

Incorporating a remote PHP file into your website using JavaScript

Is it feasible to utilize JS (jQuery) for executing a $.post from any website on any domain to a script on my server? This query stems from my reluctance to disclose my PHP files to clients (and avoid spending money on ionCube or similar solutions). By se ...

Having trouble with functions in jQuery Ajax calls to ASMX files

I have a form in my web application that submits data through an ajax call to an asmx web service. The insertion of data into the database is successful, however, neither the success nor error function seems to be triggered afterwards. The first alert mess ...

What is the reason behind the addition of '.txt' by the Next.js `Link` Component when redirecting to `href='/'` on GitHub pages?

My website is hosted on github-pages, and I am using the Link Component from Next.js to navigate within it. However, when I click on a component with the href="/", it adds .txt to the end of the URL. My website follows the /app structure. I have ...

Is it possible to use abbreviations instead of full names for object properties in a JSON string?

I'm looking for a way to efficiently convert large and repetitive javascript objects into JSON strings. With the abundance of repeating property names in these objects, I want to streamline the process by replacing those names with predefined abbrevia ...

A guide to dynamically display input fields according to the selected mat-radio button in Angular Material

I am currently utilizing angular material version 9.2.4 Within my project, I am implementing the angular material mat radio button with an input field. Each payment method will have its own corresponding input field. When the 'Cash' option is se ...