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.