Please, Help me implement lazy initialization.
I wrote Java code in Spring Core, Spring Security, and Hibernate. There are two user and Role entities. I link them with @ManyToMany(fetch = FetchType.EAGER)
. But for the task, I need to implement lazy initialization.
If I set @ManyToMany(fetch = FetchType.LAZY)
, an error occurs after successful authorization:
org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: web.model.User.roles, could not initialize proxy - no Session
Google directed to these links: First Link / Second Link
It suggests adding the user.getAuthorities () method.size();
.
Isn't this a workaround???
Then authorization is successful, but with lazy initialization, I can't access the roles. And they don't appear on the jsp page.
org.apache.jasper.JasperException: An error occurred during processing [/WEB-INF/pages/admin_panel.jsp] in line [71]
68: <td>${user.lastName}</td>
69: <td>${user.username}</td>
70: <td>${user.password}</td>
71: <td>${user.roles}</td>
72: <td>
Stacktrace:
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:617)
Below I will present the main parts of the code. If something is missing, then let me know.
My code:
User
@Entity
@Table(name = "users")
public class User implements UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "firstName")
private String firstName;
@Column(name = "lastName")
private String lastName;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@ManyToMany(fetch = FetchType.LAZY) // there was an EAGER here.
@JoinTable(name="user_role",
joinColumns={@JoinColumn(name="userId")},
inverseJoinColumns={@JoinColumn(name="roleId")})
private Set<Role> roles;
public User() {
}
...
class UserServiceImp
@Service
public class UserServiceImp implements UserService {
@Autowired
private UserDao userDao;
@Transactional
@Override
public void add(User user) {
userDao.add(user);
}
@Transactional
public List<User> listUsers() {
return userDao.listUsers();
}
@Transactional
public boolean deleteUserById(long id) {
return userDao.deleteUserById(id);
}
@Transactional(readOnly = true)
public User getUserById(long id) {
return userDao.getUserById(id);
}
@Transactional
public void update(User user) {
userDao.update(user);
}
@Transactional
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userDao.getUserByName(username);
if (user == null) {
throw new UsernameNotFoundException("User not found");
}
int size = user.getAuthorities().size(); //added this line as indicated in the links
return user;
}
}
page *.jsp
...
<c:forEach items="${users}" var="user">
<tr>
<td>${user.id}</td>
<td>${user.firstName}</td>
<td>${user.lastName}</td>
<td>${user.username}</td>
<td>${user.password}</td>
<td>${user.roles}</td>
<td>
<a href="<c:url value='${pageContext.request.contextPath}/admin/editUser?id=${user.id}'/>" >Edit</a>
|
<a href="<c:url value='${pageContext.request.contextPath}/admin/deleteUser/${user.id}'/>" >Delete</a>
</td>
</tr>
</c:forEach>
...
UserDaoImp
@Repository
public class UserDaoImp implements UserDao {
@PersistenceContext
private EntityManager manager;
...
@Override
@SuppressWarnings("unchecked")
public User getUserByName(String username) {
Query query = manager.createQuery("FROM User u WHERE u.username = : username");
query.setParameter("username", username);
try {
return (User) query.getSingleResult();
} catch (NoResultException e) {
return null;
}
}
...