Reputation: 193
At the moment I'm trying to convert my servlet-based application to a spring boot application with controllers. After I set up a filter I encountered an "could not initialize proxy - no Session"-Exception, when accessing an entities function. (Here: The users method "isAdmin").
I set up a filter like this:
public class AdminFilter implements Filter {
@Autowired
UserRepository userRepository;
@Override
@Transactional
public void doFilter(ServletRequest aRequest, ServletResponse aResponse, FilterChain aFilterChain)
throws IOException, ServletException {
User u = userRepository.getOne(5l).orElse(null);
System.out.println(u.isAdmin());
aFilterChain.doFilter(aRequest, aResponse);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
filterConfig.getServletContext());
}
@Override
public void destroy() {
}
}
Implemented the Filter interface and addded the Filter in an @Configuration tagged class to register the filter to "/admin":
@Configuration
public class SpringConfiguration {
@Bean
public FilterRegistrationBean adminRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new AdminFilter());
registration.addUrlPatterns("/admin/*");
return registration;
}
}
The Autowiring-Support is enabled by the following statement:
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
filterConfig.getServletContext());
I tried to add @Transactional to the method and also added the OpenSessionInViewFilter - without success.
In my Controller-Beans (@Controller) I can access the function of the entity retrieved from an autowired repository without any problems.
The function just returns a value from the user entity:
public boolean isAdmin() {
return admin;
}
Any ideas why I'm getting the error and how to fix it?
A stracktrace cut:
org.hibernate.LazyInitializationException: could not initialize proxy - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:148) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:266) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:73) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
at de.seeme.web.persistence.User_$$_jvst43d_a.isAdmin(User_$$_jvst43d_a.java) ~[bin/:na]
Greetings
gemorra
Upvotes: 2
Views: 2283
Reputation: 193
damn. Tried it with userRepository.find(id) and everything works fine.
With getOne you will just get a reference to the entity containing only the id (for existence checks or similiar).
Difference between CrudRepository findOne() and JpaRepository getOne()
Upvotes: 2