1
votes

When I try to save user object during registration I get following error

UserService

> @Service public class UserServiceImpl implements UserService {
> 
>     @Autowired
>     private UserRepository userRepository;
> 
>     @Autowired
>     private RoleRepository roleRepository;
> 
>     @Autowired
>     private BCryptPasswordEncoder bCryptPasswordEncoder;
> 
> 
>     @Override
>     public void save(User user) {
>         user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
>         Set<Role> roles;
>         roles = new HashSet<Role>();
>         roles.add(roleRepository.getOne(1L));
>         user.setRoles(roles);
>         userRepository.save(user);
>         userRepository.flush();
> 
>     }
> 
>     @Override
>     public User findByUsername(String username) {
>         return userRepository.findByUsername(username);
>     } }

Class User:

> @Entity 
> @Table(name = "users") public class User {
> 
>     @Id
>     @GeneratedValue(strategy = GenerationType.AUTO)
>     private Long id;
> 
>     @Column(name = "username")
>     private String username;
> 
>     @Column(name = "password")
>     private String password;
> 
>     @Transient
>     private String confirmPassword;
> 
>     @ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
>     @JoinTable(name = "user_roles", joinColumns = @JoinColumn(name = "user_id"),
>             inverseJoinColumns = @JoinColumn(name = "role_id"))
>     @JsonIgnore
>     private Set<Role> roles;
> 
>     public Long getId() {
>         return id;
>     }
> 
>     public void setId(Long id) {
>         this.id = id;
>     }
> 
>     public String getUsername() {
>         return username;
>     }
> 
>     public void setUsername(String username) {
>         this.username = username;
>     }
> 
>     public String getPassword() {
>         return password;
>     }
> 
>     public void setPassword(String password) {
>         this.password = password;
>     }
> 
>     public String getConfirmPassword() {
>         return confirmPassword;
>     }
> 
>     public void setConfirmPassword(String confirmPassword) {
>         this.confirmPassword = confirmPassword;
>     }
> 
>     public Set<Role> getRoles() {
>         return roles;
>     }
> 
>     public void setRoles(Set<Role> roles) {
>         this.roles = roles;
>     }
>     public User(){}
>     public User(String name, String pass) {
>         username = name;
>         password = pass;
>     } }

DataConfig:

> @Configuration @EnableTransactionManagement @PropertySource(value =
> {"classpath:hibernate.properties"})
> @EnableJpaRepositories("com.sergey.repository") public class
> DataConfig {
>     @Autowired
>     private Environment environment;
> 
>     @Bean
>     public DataSource dataSource() {
>         DriverManagerDataSource dataSource = new DriverManagerDataSource();
>         dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
>         dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
>         dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
>         dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
>         return dataSource;
>     }
> 
>     @Bean
>     public LocalSessionFactoryBean sessionFactory() {
>         LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
>         sessionFactory.setDataSource(dataSource());
>         sessionFactory.setPackagesToScan("com.sergey.entity");
>         sessionFactory.setHibernateProperties(hibernateProperties());
> 
>         return sessionFactory;
>     }
> 
>     private Properties hibernateProperties() {
>         Properties properties = new Properties();
>         properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
>         properties.put("show_sql", environment.getRequiredProperty("hibernate.show_sql"));
>         properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
>         return properties;
>     }
> 
>     @Bean
>     public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
>         return new PersistenceExceptionTranslationPostProcessor();
>     }
> 
>     @Bean
>     public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
>         LocalContainerEntityManagerFactoryBean emfb = new LocalContainerEntityManagerFactoryBean();
>         emfb.setDataSource(dataSource());
>         emfb.setPackagesToScan("com.sergey.entity");
>         emfb.setJpaVendorAdapter(jpaVendorAdapter());
>         emfb.setJpaProperties(hibernateProperties());
>         return emfb;
>     }
> 
>     @Bean
>     public JpaVendorAdapter jpaVendorAdapter() {
>         return new HibernateJpaVendorAdapter();
>     }
> 
>     @Bean
>     @Autowired
>     public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
>         JpaTransactionManager transactionManager = new JpaTransactionManager();
>         transactionManager.setEntityManagerFactory(emf);
>         return transactionManager;
>     } }

UserRepositoty:

> public interface UserRepository extends JpaRepository<User, Long> {
>     User findByUsername(String username); }

UserController:

> public class UsersController {
> 
>     @Autowired
>     private UserService userService;
> 
>     @Autowired
>     private SecurityService securityService;
> 
>     @Autowired
>     private UserValidator userValidator;
> 
>     @RequestMapping(value = "/registration", method = RequestMethod.GET)
>     public String registration(Model model) {
>         model.addAttribute("userForm", new User());
> 
>         return "registration";
>     }
> 
>     @RequestMapping(value = "/registration", method = RequestMethod.POST)
>     public String registration(@ModelAttribute("userForm") User userForm, BindingResult bindingResult, Model model) {
>         userValidator.validate(userForm, bindingResult);
> 
>         if (bindingResult.hasErrors()) {
>             return "registration";
>         }
> 
>         userService.save(userForm);
> 
>         securityService.autoLogin(userForm.getUsername(), userForm.getConfirmPassword());
> 
>         return "redirect:/welcome";
>     }
> 
>     @RequestMapping(value = "/login", method = RequestMethod.GET)
>     public String login(Model model, String error, String logout) {
>         if (error != null) {
>             model.addAttribute("error", "Username or password is incorrect.");
>         }
> 
>         if (logout != null) {
>             model.addAttribute("message", "Logged out successfully.");
>         }
> 
>         return "login";
>     }
> 
>     @RequestMapping(value = {"/", "/welcome"}, method = RequestMethod.GET)
>     public String welcome(Model model) {
>         return "welcome";
>     }
> 
>     @RequestMapping(value = "/admin", method = RequestMethod.GET)
>     public String admin(Model model) {
>         return "admin";
>     } }

Jsp:

> <div class="container">
> 
>     <form:form method="POST" modelAttribute="userForm" class="form-signin">
>         <h2 class="form-signin-heading">Create your account</h2>
>         <spring:bind path="username">
>             <div class="form-group ${status.error ? 'has-error' : ''}">
>                 <form:input type="text" path="username" class="form-control" placeholder="Username"
>                             autofocus="true"></form:input>
>                 <form:errors path="username"></form:errors>
>             </div>
>         </spring:bind>
> 
>         <spring:bind path="password">
>             <div class="form-group ${status.error ? 'has-error' : ''}">
>                 <form:input type="password" path="password" class="form-control" placeholder="Password"></form:input>
>                 <form:errors path="password"></form:errors>
>             </div>
>         </spring:bind>
> 
>         <spring:bind path="confirmPassword">
>             <div class="form-group ${status.error ? 'has-error' : ''}">
>                 <form:input type="password" path="confirmPassword" class="form-control"
>                             placeholder="Confirm your password"></form:input>
>                 <form:errors path="confirmPassword"></form:errors>
>             </div>
>         </spring:bind>
> 
>         <button class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
>     </form:form>
> 
> </div>

Error, then add users:

org.springframework.dao.InvalidDataAccessApiUsageException: uninitialized proxy passed to persist(); nested exception is org.hibernate.PersistentObjectException: uninitialized proxy passed to persist() org.springframework.orm.hibernate5.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:265) org.springframework.orm.hibernate5.HibernateExceptionTranslator.convertHibernateAccessException(HibernateExceptionTranslator.java:65) org.springframework.orm.hibernate5.HibernateExceptionTranslator.translateExceptionIfPossible(HibernateExceptionTranslator.java:52) org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59) org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213) org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92) org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213) com.sun.proxy.$Proxy47.save(Unknown Source) com.sergey.service.Impl.UserServiceImpl.save(UserServiceImpl.java:35) com.sergey.controller.UsersController.registration(UsersController.java:42) sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) java.lang.reflect.Method.invoke(Unknown Source) org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) javax.servlet.http.HttpServlet.service(HttpServlet.java:650) org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) javax.servlet.http.HttpServlet.service(HttpServlet.java:731) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:126) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:114) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:122) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:169) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:48) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter.doFilter(DefaultLoginPageGeneratingFilter.java:162) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:205) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330) org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)

What could be a reason for this execption??

1

1 Answers

-1
votes

Try adding OpenEntityManagerInViewFilter from spring in your web.xml

<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
    org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
<init-param>
    <param-name>entityManagerFactoryBeanName</param-name>
    <param-value>entityManagerFactory</param-value>
</init-param>
</filter>
<filter-mapping>
    <filter-name>hibernateFilter</filter-name>
    <url-pattern>/services/*</url-pattern>
</filter-mapping>