I use Spring Social Twitter v. 1.1.0.M4. I successfully enabled in-memory connections to Twitter. Now I'm trying to persist the connections. My database connection and logging seems to be working, as the user is authenticated and I can see their twitter login. The problem is, I can't access any of their details (tweeds, followed, etc.). The code I have in my controller to show user's tweets is:
#Autowired
private Twitter twitter;
#Autowired
private TwitterConnectionUtils twitterConnectionUtils;
#Autowired
private SessionBean sessionBean;
#RequestMapping("/")
public String index(Model model) {
logger.warning("index");
model.addAttribute("sessionBean", sessionBean);
List<Tweet> tweets = new ArrayList<Tweet>();
try {
if (!twitterConnectionUtils.isConnectedToTwitter()) {
return "index";
}
tweets.addAll(twitter.timelineOperations().getHomeTimeline());
} catch (Exception e) {
logger.warning(ExceptionUtils.getStackTrace(e));
model.addAttribute("exception", e.toString());
return "index";
}
model.addAttribute("tweets", tweets);
return "twitter/tweets";
}
The exception is thrown in line tweets.addAll(twitter.timelineOperations().getHomeTimeline());. twitter is not null but at the same time I can't invoke any methods on it (e.g. toString), because I'm getting NPE immediately. Here's the stacktrace of the error obtained in logger.warning(ExceptionUtils.getStackTrace(e));:
WARNING: java.lang.NullPointerException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy16.timelineOperations(Unknown Source)
at agh.sr.tweedle.controller.TweetsController.index(TweetsController.java:43)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:219)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:100)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:604)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:565)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:947)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1009)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:724)
Any ideas what might be causing the problem? I also include my javaconfig for the library, for reference:
#Configuration
#EnableTwitter(appId="myAppId", appSecret="myAppSecret")
public class TwitterConfig {
#Autowired
private TwitterConnectInterceptor twitterConnectInterceptor;
#Inject
private DataSource dataSource;
#Inject
private Environment environment;
#Bean
public UserIdSource userIdSource() {
return new UserIdSource() {
#Override
public String getUserId() {
return "myTestingPurposesLogin"; // TODO change to security-obtained user login
}
};
}
#Bean
public ConnectController connectController() {
CustomConnectController connectionController =
new CustomConnectController(connectionFactoryLocator(), connectionRepository());
connectionController.addInterceptor(twitterConnectInterceptor);
return connectionController;
}
#Bean
public ConnectionFactoryLocator connectionFactoryLocator() {
ConnectionFactoryRegistry registry = new ConnectionFactoryRegistry();
registry.addConnectionFactory(new TwitterConnectionFactory(
"myAppId", "myAppSecret"));
return registry;
}
#Bean
#Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public ConnectionRepository connectionRepository() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null) {
throw new IllegalStateException("Unable to get a ConnectionRepository: no user signed in");
}
return usersConnectionRepository().createConnectionRepository(authentication.getName());
}
#Bean
public UsersConnectionRepository usersConnectionRepository() {
return new JdbcUsersConnectionRepository(dataSource, connectionFactoryLocator(),
textEncryptor());
}
#Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
}
Change
tweets.addAll(twitter.timelineOperations().getHomeTimeline());
To something like (pseudocode, I don't know all of the types being returned):
var timelineOperations = twitter.TimelineOperations();
var homeTimeline = timelineOperations.GetHomeTimeline();
tweets.addAll(homeTimeline);
This will tell you which method call is not returning an object.
Alright, I was doing it downright wrong! Here's the easy-to-follow working example:
#Configuration
#EnableTwitter(appId="myAppId", appSecret="myAppSecret")
#EnableJdbcConnectionRepository
public class TwitterConfig {
#Autowired
private TwitterConnectInterceptor twitterConnectInterceptor;
#Bean
public UserIdSource userIdSource() {
return new UserIdSource() {
#Override
public String getUserId() {
return "myTestingPurposesLogin";
}
};
}
#Bean
public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
CustomConnectController connectionController = new CustomConnectController(connectionFactoryLocator, connectionRepository);
connectionController.addInterceptor(twitterConnectInterceptor);
return connectionController;
}
#Bean
public TextEncryptor textEncryptor() {
return Encryptors.noOpText();
}
}
The #EnableJdbcConnectionRepository annotation was crucial to get me on the right track.
Related
I have a page in which user can edit its profile including username. I can get User model with the help of #AuthenticationPrincipal using the below controller:-
#RequestMapping(value = "/editCustomerProfile", method = RequestMethod.GET)
public String editCustomerProfileGet(#AuthenticationPrincipal User activeUser,Locale locale, Model model) {
Customer customer = customerService.getCustomerByUsername(activeUser.getUsername());
model.addAttribute("customer", customer);
return "editCustomer";
}
Update controller method as below:-
#RequestMapping(value = "/updateCustomer", method = RequestMethod.POST)
public String updateCustomerProfilePost(#Valid #ModelAttribute("customer") Customer customer, BindingResult result, Model model, HttpServletRequest request){
customerFormValidator.validate(customer, result);
if(result.hasErrors()){
model.addAttribute("customer", customer);
return "editCustomer";
}
List<Customer> customerList = customerService.getAllCustomers();
for (int i=0; i< customerList.size(); i++){
if(customer.getUsername().equals(customerList.get(i).getUsername())){
model.addAttribute("usernameMsg", "Username already exists");
model.addAttribute("customer", customer);
return "editCustomer";
}
}
Customer existingCustomer=customerService.getCustomerById(customer.getCutomerId());
existingCustomer.setCustomerName(customer.getCustomerName());
existingCustomer.setBillingAddress(customer.getBillingAddress());
existingCustomer.getBillingAddress().setCustomer(existingCustomer);
existingCustomer.setShippingAddress(customer.getShippingAddress());
existingCustomer.getShippingAddress().setCustomer(existingCustomer);
existingCustomer.setUsername(customer.getUsername());
existingCustomer.getUser().setUsername(customer.getUsername());
Customer editedCustomer=customerService.updateCustomer(existingCustomer);
customerSecurityService.updateEditCustomerUserAuthentication(editedCustomer, request);
model.addAttribute("message", "Customer Information Updated Successfully.");
return "editCustomerSuccess";//information page
}
Used method of CustomerSecurityServiceImpl as below:-
#Override
public void updateEditCustomerUserAuthentication(Customer customer, HttpServletRequest request) {
final Users user = customer.getUser();
final Authorities authorities = customerService.getUserAuthoritiesById(user.getUsersId());
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user.getUsername(),null, Arrays.asList(new SimpleGrantedAuthority(authorities.getAuthority())));
result.setDetails(user);
SecurityContextHolder.getContext().setAuthentication(result);
}
Error after user profile change once and try again raise error as below:-
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/MusicStore] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException
at com.emusicstore.controller.RegisterController.editCustomerProfileGet(RegisterController.java:291)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:806)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:729)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1096)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:674)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1500)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1456)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
After editing the user information, it is reflecting correctly but when I again try to edit the same user then #AuthenticationPrincipal active user return null. Please advice me how I do add the user in authentication principle to reuse the above editCustomerProfileGet method.
Thank you very much.
Actually you have passed username as a principal in authentication token, whereas User object needs to be passed which will be used in subsequent authentication calls internally.
Change your code to
UsernamePasswordAuthenticationToken result = new UsernamePasswordAuthenticationToken(user,user.getPassword(), Arrays.asList(new SimpleGrantedAuthority(authorities.getAuthority())));
SEVERE: Servlet.service() for servlet [appServlet] in context with path [/byuhtools] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]; nested exception is java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]] with root cause
java.lang.IllegalArgumentException: Timestamp format must be yyyy-mm-dd hh:mm:ss[.fffffffff]
at java.sql.Timestamp.valueOf(Timestamp.java:204)
at oracle.jdbc.driver.CharCommonAccessor.getTimestamp(CharCommonAccessor.java:544)
at oracle.jdbc.driver.T4CVarcharAccessor.getTimestamp(T4CVarcharAccessor.java:947)
at oracle.jdbc.driver.OracleResultSetImpl.getTimestamp(OracleResultSetImpl.java:1422)
at oracle.jdbc.driver.OracleResultSet.getTimestamp(OracleResultSet.java:512)
at org.hibernate.type.descriptor.sql.TimestampTypeDescriptor$2.doExtract(TimestampTypeDescriptor.java:67)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:64)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:261)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:247)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:332)
at org.hibernate.type.ComponentType.hydrate(ComponentType.java:641)
at org.hibernate.type.ComponentType.nullSafeGet(ComponentType.java:349)
at org.hibernate.type.ManyToOneType.hydrate(ManyToOneType.java:176)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2912)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1672)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1604)
at org.hibernate.loader.Loader.getRow(Loader.java:1504)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:712)
at org.hibernate.loader.Loader.processResultSet(Loader.java:942)
at org.hibernate.loader.Loader.doQuery(Loader.java:910)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:341)
at org.hibernate.loader.Loader.doList(Loader.java:2522)
at org.hibernate.loader.Loader.doList(Loader.java:2508)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2338)
at org.hibernate.loader.Loader.list(Loader.java:2333)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:490)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:355)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:195)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1269)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:101)
at org.hibernate.ejb.QueryImpl.getResultList(QueryImpl.java:264)
at edu.byuh.universitytools.ps.dao.PsMajorDaoImpl.findAll(PsMajorDaoImpl.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy102.findAll(Unknown Source)
at edu.byuh.universitytools.ps.service.PsStudInfoService.getStudInfo(PsStudInfoService.java:18)
at edu.byuh.universitytools.controller.FacultyController.getFacultyHome(FacultyController.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:213)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:126)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:96)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:617)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:578)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:923)
at edu.byuh.universitytools.servlet.UniversityToolsServlet.doDispatch(UniversityToolsServlet.java:46)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:624)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:731)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:183)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.jasig.cas.client.session.SingleSignOutFilter.doFilter(SingleSignOutFilter.java:65)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:436)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
I have trouble in getting the query for encountering this error.
No matter what I did on the attribute, effDate, either change it to type Date or Timestamp, even use #temporal annotation, it just did not work and keep complaining about the same problem.
By the way, this is a embedded key model. I don't know if it matters or not.
Here is what I do in my model. Please help me find where I did wrong.
import java.io.Serializable;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import javax.persistence.Column;
public class PsMajorKey implements Serializable {
private static final long serialVersionUID = 3426630990033657842L;
#Column (name = "acad_plan")
private String major;
#Column (name = "institution")
private String institution;
#Column (name = "effdt")
private Timestamp effDate;
#Column (name = "descr")
private String descr;
public String getMajor() {
return this.major;
}
public String getInstituion() {
return this.institution;
}
public Timestamp getEffDate() {
return this.effDate;
}
public String getDescr() {
return this.descr;
}
public String getEffDateStr() {
if (getEffDate() != null) {
return new SimpleDateFormat("yyyy-MMM-dd hh:mm a").format(this.effDate.getTime());
} else {
return "";
}
}
public boolean equals (Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof PsMajorKey)) {
return false;
}
if (obj == null || this.getClass() != obj.getClass()) {
return false;
}
final PsMajorKey key = (PsMajorKey) obj;
if (key.major.equals(this.major) && key.institution.equals(this.institution) && key.effDate.equals(this.getEffDateStr())) {
return true;
} else {
return false;
}
}
public int hashCode() {
return (int) major.hashCode() + (int) institution.hashCode() + (int) getEffDateStr().hashCode();
}
}
In my spring application, I am using json-taglibs to dinamically generate json files based on Lists of entities I retrieve from database and add to request in my controller. I am facing this error with one of this files:
Grave: Servlet.service() for servlet [json_dispatcher] in context with path [/loja] threw exception [Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateSystemException: could not get a field value by reflection getter of com.spring.webapp.lojavirtual.common.persistence.model.Categoria.id; nested exception is org.hibernate.PropertyAccessException: could not get a field value by reflection getter of com.spring.webapp.lojavirtual.common.persistence.model.Categoria.id] with root cause
java.lang.IllegalArgumentException: Can not set java.lang.Integer field com.spring.webapp.lojavirtual.common.persistence.model.Categoria.id to java.lang.String
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:164)
at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:168)
at sun.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:55)
at sun.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36)
at java.lang.reflect.Field.get(Field.java:379)
at org.hibernate.property.DirectPropertyAccessor$DirectGetter.get(DirectPropertyAccessor.java:57)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:346)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:4746)
at org.hibernate.persister.entity.AbstractEntityPersister.isTransient(AbstractEntityPersister.java:4465)
at org.hibernate.engine.internal.ForeignKeys.isTransient(ForeignKeys.java:243)
at org.hibernate.engine.internal.ForeignKeys.getEntityIdentifierIfNotUnsaved(ForeignKeys.java:293)
at org.hibernate.type.EntityType.getIdentifier(EntityType.java:537)
at org.hibernate.type.ManyToOneType.nullSafeSet(ManyToOneType.java:174)
at org.hibernate.param.NamedParameterSpecification.bind(NamedParameterSpecification.java:67)
at org.hibernate.loader.hql.QueryLoader.bindParameterValues(QueryLoader.java:613)
at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1900)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1861)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1838)
at org.hibernate.loader.Loader.doQuery(Loader.java:909)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:354)
at org.hibernate.loader.Loader.doList(Loader.java:2553)
at org.hibernate.loader.Loader.doList(Loader.java:2539)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2369)
at org.hibernate.loader.Loader.list(Loader.java:2364)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:496)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:387)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:231)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1264)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:103)
at com.spring.webapp.lojavirtual.config.hibernate.Dao.findByField(Dao.java:67)
at com.spring.webapp.lojavirtual.config.hibernate.Dao$$FastClassBySpringCGLIB$$75e094d4.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
at com.spring.webapp.lojavirtual.produto.persistence.ProdutoDao$$EnhancerBySpringCGLIB$$b13352aa.findByField(<generated>)
at com.spring.webapp.lojavirtual.produto.service.ProdutoService.listagem_por_categoria(ProdutoService.java:105)
at com.spring.webapp.lojavirtual.produto.service.ProdutoService$$FastClassBySpringCGLIB$$5e9076b4.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:711)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:644)
at com.spring.webapp.lojavirtual.produto.service.ProdutoService$$EnhancerBySpringCGLIB$$c1e4b579_2.listagem_por_categoria(<generated>)
at com.spring.webapp.lojavirtual.produto.controller.ProdutoControler.listagem_por_categoria_json(ProdutoControler.java:100)
at com.spring.webapp.lojavirtual.produto.controller.ProdutoControler$$FastClassBySpringCGLIB$$d626f2a4.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:640)
at com.spring.webapp.lojavirtual.produto.controller.ProdutoControler$$EnhancerBySpringCGLIB$$e007cea4_3.listagem_por_categoria_json(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
the file presenting this error is:
<%# taglib prefix="json" uri="http://www.atg.com/taglibs/json" %>
<json:object>
<json:array name="produto" var="item" items="${lista}">
<json:object>
<json:property name="id" value="${item.id}"/>
<json:property name="nome" value="${item.nome}"/>
<json:property name="categoria" value="${item.categoria}"/>
</json:object>
</json:array>
</json:object>
and the method from controller which map this file is:
#RequestMapping(value="listagem.json")
public ModelAndView listagem_json() {
ModelAndView mav = new ModelAndView();
mav.addObject("lista", produto.listagem());
mav.setViewName("listagem_produto");
return mav;
}
#RequestMapping(value="listagem_por_categoria.json", method=RequestMethod.GET)
public ModelAndView listagem_por_categoria_json(HttpServletRequest request, HttpServletResponse response) {
String id_categoria = request.getParameter("id");
ModelAndView mav = new ModelAndView();
if(id_categoria == null)
mav.addObject("lista", produto.listagem());
else
mav.addObject("lista", produto.listagem_por_categoria(id_categoria));
mav.setViewName("listagem_produto");
return mav;
}
Note: the error only is triggered when I call the second method. The methods listagem() and listagem_por_categoria() from my service class are implemented this way:
#Transactional
public List<Produto> listagem() {
return produto.findAll();
}
#Transactional
public Produto listagem(int id) {
return produto.findById(id);
}
#Transactional
public List<Produto> listagem_por_categoria(String id_categoria) {
return produto.findByField("categoria", id_categoria);
}
and in my DAO class, the methods findAll(), findById() and findByField(), are implemented this way:
#SuppressWarnings("unchecked")
#Transactional
public E findById(int id) {
E instance = (E) sessionFactory.getCurrentSession().get(entity, id);
return instance;
}
#SuppressWarnings("unchecked")
#Transactional
public List<E> findByField(String field, String value) {
String expressao = entity.toString();
String nome_classe = new String();
StringTokenizer st = new StringTokenizer(expressao);
while (st.hasMoreTokens()) {
nome_classe = st.nextToken();
}
String query = "from "+nome_classe+" where "+field+" = :data";
Query q = sessionFactory.getCurrentSession().createQuery(query);
q.setParameter("data", value);
List<E> instance = q.list();
return instance;
}
#SuppressWarnings("unchecked")
#Transactional
public List<E> findAll() {
return (List<E>) sessionFactory.getCurrentSession().createCriteria(entity).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
}
anyone can see what's wrong with all that implementations?
Check this lines
String query = "from "+nome_classe+" where "+field+" = :data";
q.setParameter("data", value);
You pass value as a String, when hibernate construct a query it it replace a parameter with String. I think for category.Id you are using int type.
Logic is following:
It expects Id as int and instead it gets String, then you got an exception.
upd:
If you don't want change implementation dramatically use setParameter(String name, Object val, Type type) to set column value correctly.
To get type use sessionFactory.getClassMetadata(Class.class).getPropertyType("filedName")
Then I solve this problem by implementing two variations for the method findByField, one which accepts a String value, and other an Integer. The final code for this methods are:
#SuppressWarnings("unchecked")
#Transactional
public List<E> findByStringField(String field, String value) {
String expressao = entity.toString();
String nome_classe = new String();
StringTokenizer st = new StringTokenizer(expressao);
while (st.hasMoreTokens()) {
nome_classe = st.nextToken();
}
String query = "from "+nome_classe+" where "+field+" = :data";
List<E> instance = sessionFactory.getCurrentSession().createQuery(query).setString("data", value).list();
return instance;
}
#SuppressWarnings("unchecked")
#Transactional
public List<E> findByIntegerField(String field, Integer value) {
String expressao = entity.toString();
String nome_classe = new String();
StringTokenizer st = new StringTokenizer(expressao);
while (st.hasMoreTokens()) {
nome_classe = st.nextToken();
}
String query = "from "+nome_classe+" where "+field+" = :data";
List<E> instance = sessionFactory.getCurrentSession().createQuery(query).setInteger("data", value).list();
return instance;
}
In my spring project, I have implemented a generic class to serve as base for all my Dao class. By example, my class UsuarioHome have this code:
#Repository
public class UsuarioHome extends Dao<Usuario> {
public UsuarioHome() {
super(Usuario.class);
}
}
and my generic class has this code:
public class Dao<E> {
private final E entity;
#Autowired
SessionFactory sessionFactory;
protected Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
public Dao(E entity) {
this.entity = entity;
}
#SuppressWarnings("unchecked")
public Dao(Class<?> classe) {
this.entity = (E) classe;
}
public E getEntity() {
return this.entity;
}
#Transactional
public boolean persist(E transientInstance) {
try {
sessionFactory.getCurrentSession().persist(transientInstance);
return true;
} catch (RuntimeException re) {
return false;
}
}
#Transactional
public boolean remove(E transientInstance) {
try {
sessionFactory.getCurrentSession().delete(transientInstance);
return true;
} catch (RuntimeException re) {
return false;
}
}
#Transactional
public boolean merge(E detachedInstance) {
try {
sessionFactory.getCurrentSession().merge(detachedInstance);
return true;
} catch (RuntimeException re) {
return false;
}
}
#SuppressWarnings("unchecked")
#Transactional
public E findById(int id) {
try {
E instance = (E) sessionFactory.getCurrentSession().get(entity.getClass(), id);
return instance;
} catch (RuntimeException re) {
return null;
}
}
#SuppressWarnings("unchecked")
#Transactional
public E findByField(String field, String value) {
try {
String expressao = entity.toString();
String nome_classe = new String();
StringTokenizer st = new StringTokenizer(expressao);
while (st.hasMoreTokens()) {
nome_classe = st.nextToken();
}
String query = "from "+nome_classe+" where "+field+" = :data";
Query q = sessionFactory.getCurrentSession().createQuery(query);
q.setParameter("data", value);
E instance = (E) q.uniqueResult();
return instance;
} catch (RuntimeException re) {
return null;
}
}
#SuppressWarnings("unchecked")
#Transactional
public List<E> findAll() {
try {
List<E> instance = sessionFactory.getCurrentSession().createCriteria(entity.getClass()).list();
return instance;
} catch (RuntimeException re) {
return null;
}
}
}
But, when I need retrieve a list of all items from the table, I am receiving 0 items. The method for do this is placed in my class UsuarioService:
#Transactional
public List<Usuario> listagem_usuarios() {
return usuario.findAll();
}
where I autowires my Dao class:
#Autowired
private UsuarioHome usuario;
#Autowired
private GrupoPermissaoHome grupo_permissao;
Anyone can tell what I am doing wrong here? I tested this solution in other projects (simpler than that), and it work.
UPDATE
When I try run the application, I am facing a cast error, like this, by example, when this json page is opened:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="json" uri="http://www.atg.com/taglibs/json" %>
<json:object>
<c:forEach var="item" items="${lista}">
<json:object name="usuario">
<json:property name="id" value="${item.id}"/>
<json:property name="login" value="${item.login}"/>
<json:property name="pnome" value="${item.first_name}"/>
<json:property name="unome" value="${item.last_name}"/>
<json:property name="email" value="${item.email}"/>
</json:object>
</c:forEach>
</json:object>
the console shows this error:
Grave: Servlet.service() for servlet jsp threw exception
java.lang.NumberFormatException: For input string: "id"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at javax.el.ArrayELResolver.coerce(ArrayELResolver.java:166)
at javax.el.ArrayELResolver.getValue(ArrayELResolver.java:46)
at org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:104)
at org.apache.el.parser.AstValue.getValue(AstValue.java:183)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:1026)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp._jspx_meth_json_005fproperty_005f0(listagem_005fusuarios_jsp.java:168)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp.access$1(listagem_005fusuarios_jsp.java:156)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp$Helper.invoke1(listagem_005fusuarios_jsp.java:271)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp$Helper.invoke(listagem_005fusuarios_jsp.java:310)
at atg.taglib.json.JsonObjectTag.doTag(JsonObjectTag.java:63)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp._jspx_meth_json_005fobject_005f1(listagem_005fusuarios_jsp.java:151)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp._jspx_meth_c_005fforEach_005f0(listagem_005fusuarios_jsp.java:117)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp.access$0(listagem_005fusuarios_jsp.java:98)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp$Helper.invoke0(listagem_005fusuarios_jsp.java:261)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp$Helper.invoke(listagem_005fusuarios_jsp.java:307)
at atg.taglib.json.JsonObjectTag.doTag(JsonObjectTag.java:63)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp._jspx_meth_json_005fobject_005f0(listagem_005fusuarios_jsp.java:93)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp._jspService(listagem_005fusuarios_jsp.java:68)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Mai 20, 2014 7:40:22 AM org.apache.catalina.core.StandardWrapperValve invoke
Grave: Servlet.service() for servlet [json_dispatcher] in context with path [/loja] threw exception [An exception occurred processing JSP page /WEB-INF/view/json/listagem_usuarios.jsp at line 5
2: <%# taglib prefix="json" uri="http://www.atg.com/taglibs/json" %>
3: <json:object>
4: <c:forEach var="item" items="${lista}">
5: <json:object name="usuario">
6: <json:property name="id" value="${item.id}"/>
7: <json:property name="login" value="${item.login}"/>
8: <json:property name="pnome" value="${item.first_name}"/>
Stacktrace:] with root cause
java.lang.NumberFormatException: For input string: "id"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.lang.Integer.parseInt(Integer.java:527)
at javax.el.ArrayELResolver.coerce(ArrayELResolver.java:166)
at javax.el.ArrayELResolver.getValue(ArrayELResolver.java:46)
at org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:104)
at org.apache.el.parser.AstValue.getValue(AstValue.java:183)
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:185)
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:1026)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp._jspx_meth_json_005fproperty_005f0(listagem_005fusuarios_jsp.java:168)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp.access$1(listagem_005fusuarios_jsp.java:156)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp$Helper.invoke1(listagem_005fusuarios_jsp.java:271)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp$Helper.invoke(listagem_005fusuarios_jsp.java:310)
at atg.taglib.json.JsonObjectTag.doTag(JsonObjectTag.java:63)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp._jspx_meth_json_005fobject_005f1(listagem_005fusuarios_jsp.java:151)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp._jspx_meth_c_005fforEach_005f0(listagem_005fusuarios_jsp.java:117)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp.access$0(listagem_005fusuarios_jsp.java:98)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp$Helper.invoke0(listagem_005fusuarios_jsp.java:261)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp$Helper.invoke(listagem_005fusuarios_jsp.java:307)
at atg.taglib.json.JsonObjectTag.doTag(JsonObjectTag.java:63)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp._jspx_meth_json_005fobject_005f0(listagem_005fusuarios_jsp.java:93)
at org.apache.jsp.WEB_002dINF.view.json.listagem_005fusuarios_jsp._jspService(listagem_005fusuarios_jsp.java:68)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:749)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:487)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:412)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:339)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:146)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
UPDATE 2
After more tests, I verify that when I use:
List<E> instance = sessionFactory.getCurrentSession().createCriteria(entity.getClass()).list();
I get an empty list. But when I use:
List<E> instance = (List<E>) sessionFactory.getCurrentSession().createSQLQuery("select * from usuario").list();
I get the data from database, but I can access them, due to an cast error (explained above in the first update)
ps.: the other methods, findById and findByField, are working fine.
Ok, I solve this issue following the sugestion from this topic:
Class derived from generic class don't get the correct type
the final code for the Dao template it's that:
public class Dao<E> {
private final Class<E> entity;
#Autowired
protected SessionFactory sessionFactory;
protected Session getCurrentSession(){
return sessionFactory.getCurrentSession();
}
/*public Dao(E entity) {
this.entity = entity;
}*/
public Dao(Class<E> classe) {
this.entity = classe;
}
/*public E getEntity() {
return this.entity;
}*/
#Transactional
public boolean persist(E transientInstance) {
sessionFactory.getCurrentSession().persist(transientInstance);
return true;
}
#Transactional
public boolean remove(E transientInstance) {
sessionFactory.getCurrentSession().delete(transientInstance);
return true;
}
#Transactional
public boolean merge(E detachedInstance) {
sessionFactory.getCurrentSession().merge(detachedInstance);
return true;
}
#Transactional
public E findById(int id) {
E instance = (E) sessionFactory.getCurrentSession().get(entity.getClass(), id);
return instance;
}
#Transactional
public E findByField(String field, String value) {
String expressao = entity.toString();
String nome_classe = new String();
StringTokenizer st = new StringTokenizer(expressao);
while (st.hasMoreTokens()) {
nome_classe = st.nextToken();
}
String query = "from "+nome_classe+" where "+field+" = :data";
Query q = sessionFactory.getCurrentSession().createQuery(query);
q.setParameter("data", value);
E instance = (E) q.uniqueResult();
return instance;
}
#Transactional
public List<E> findAll() {
return (List<E>) sessionFactory.getCurrentSession().createCriteria(entity).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
}
}
I´m getting a lazy initialization exception. A have a controller method with the annotation #Transactional, it invokes a service method ( it not has the #Transactional annotation), and finally inside that method I invoke another spring component (it checks if the user has the proper role).
In the project I used the #Transactional and i have no problems. But in this case i have the lazy initialization exception.
Am I missing something?
Here is the code:
and here is the method that is first executed. It has the #Transactional annotation
#Transactional
public CompanyForm edit(){
CompanyForm form = new CompanyForm();
Company company = companyService.findMainOne(getLoggedUser());
if (company != null) {
if (company != null)
modelMapper.map(company, form);
}
return form;
}
This is the method in a service where the code is called
#Autowired
private UserVisitorHasBussinessRole hasBussinessRole;
#Override
public Company findMainOne(User user) {
if (user == null)
throw new NullPointerException("the user can not be null");
user.accept(hasBussinessRole);
List<Company> companies = this.companyRepository.findOwnedBy(user
.getId());
if (companies != null && companies.size() > 0)
return companies.get(0);
return null;
}
This component checks if the user has the proper role. This is where i got the exception
#Component
public class UserVisitorHasBussinessRole implements UserVisitor {
#Autowired
private Messages messages;
#Override
public void visit(SystemUser user) {
if(user == null || user.getUserRoles() == null || user.getUserRoles().isEmpty())
{
String message = messages.get("hasBussinesRoleVisitor.noRole");
throw new RuntimeException(message);
}
Boolean hasRole = false;
for (UserRole role : user.getUserRoles()) {
if(role instanceof UserRoleBusiness){
hasRole = true;
break;
}
}
if(!hasRole)
{
String message = messages.get("hasBussinesRoleVisitor.noRole");
throw new RuntimeException(message);
}
}
#Override
public void visit(SocialUser user) {
String message = messages.get("hasBussinesRoleVisitor.noRole");
throw new RuntimeException(message);
}
}
This is where the exception is thrown
user.getUserRoles().isEmpty()
The entity:
#Entity
#DiscriminatorValue(value = "BU")
public class SystemUser extends User {
/**
*
*/
private static final long serialVersionUID = 3845147625976106863L;
// for joing the tables (many-to-many)
#ManyToMany(cascade = CascadeType.ALL, targetEntity = UserRole.class)
#JoinTable(name = "systemUser_userRole", joinColumns = { #JoinColumn(name = "system_user_id") }, inverseJoinColumns = { #JoinColumn(name = "role_Id") })
private List<UserRole> userRoles;
/**
* the list of user roles
* #return the user roles
*/
public List<UserRole> getUserRoles() {
return userRoles;
}
/***
* set the list of user roles
* #param userRoles the user roles
*/
public void setUserRoles(List<UserRole> userRoles) {
this.userRoles = userRoles;
}
}
I'm getting the following exception
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at ar.com.held.model.user.User.accept(Unknown Source)
at ar.com.held.service.implementation.CompanyServiceImpl.findMainOne(Unknown Source)
at ar.com.held.service.implementation.CompanyServiceImpl$$FastClassByCGLIB$$d0027e0c.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at ar.com.held.service.implementation.CompanyServiceImpl$$EnhancerByCGLIB$$b15b3940_2.findMainOne(<generated>)
at ar.com.held.controller.CompanyFlowController.edit(CompanyFlowController.java:28)
at ar.com.held.controller.CompanyFlowController$$FastClassByCGLIB$$c3823c4.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at ar.com.held.controller.CompanyFlowController$$EnhancerByCGLIB$$5b3921c7_2.edit(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.expression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:69)
at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:109)
at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:57)
at org.springframework.expression.spel.ast.SpelNodeImpl.getTypedValue(SpelNodeImpl.java:102)
at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:97)
at org.springframework.binding.expression.spel.SpringELExpression.getValue(SpringELExpression.java:84)
at org.springframework.webflow.action.EvaluateAction.doExecute(EvaluateAction.java:75)
at org.springframework.webflow.action.AbstractAction.execute(AbstractAction.java:188)
at org.springframework.webflow.execution.AnnotatedAction.execute(AnnotatedAction.java:145)
at org.springframework.webflow.execution.ActionExecutor.execute(ActionExecutor.java:51)
at org.springframework.webflow.engine.ActionList.execute(ActionList.java:155)
at org.springframework.webflow.engine.Flow.start(Flow.java:534)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.start(FlowExecutionImpl.java:366)
at org.springframework.webflow.engine.impl.FlowExecutionImpl.start(FlowExecutionImpl.java:225)
at org.springframework.webflow.executor.FlowExecutorImpl.launchExecution(FlowExecutorImpl.java:140)
at org.springframework.webflow.mvc.servlet.FlowHandlerAdapter.handle(FlowHandlerAdapter.java:193)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:900)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:827)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.opensymphony.sitemesh.webapp.SiteMeshFilter.obtainContent(SiteMeshFilter.java:129)
at com.opensymphony.sitemesh.webapp.SiteMeshFilter.doFilter(SiteMeshFilter.java:77)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:311)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:224)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:169)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:927)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:987)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:309)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: ar.com.held.model.user.SystemUser.userRoles, no session or session was closed
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:393)
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:385)
at org.hibernate.collection.internal.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:125)
at org.hibernate.collection.internal.PersistentBag.isEmpty(PersistentBag.java:249)
at ar.com.held.service.implementation.visitor.UserVisitorHasBussinessRole.visit(Unknown Source)
... 100 more
I solved using #LazyCollection(LazyCollectionOption.FALSE)
here is the code:
#ManyToMany(cascade = CascadeType.ALL, targetEntity = UserRole.class)
#JoinTable(name = "systemUser_userRole", joinColumns = { #JoinColumn(name = "system_user_id") }, inverseJoinColumns = { #JoinColumn(name = "role_Id") })
#LazyCollection(LazyCollectionOption.FALSE)
private List<UserRole> userRoles;
It is not the best solution but it works. The problem is that LazyCollection annotation is a Hibernate annotation and not a jpa one.
Thanks to all
This happens when a lazy initialized object is read when the original transaction is already completed. In other words, when you return something from a method with #Transactional annotation all objects must be initialized (no way to access lazy objects after returning from the method). So use lazy="false" in this case to resolve the issue (or force lazy initialization inside the method).
Add #Transactional to findMainOne and visit(SystemUser) so they both participate in the same transaction, thus giving them access to the session/entity-manager for lazily-loading related components. Or you can load those components that might be needed before calling findMainOne.