org.hibernate.PersistentObjectException: uninitialized proxy passed to persist()
<p>When I try to save user object during registration I get following error</p>

<p><strong>UserService</strong></p>

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

<p><strong>Class User:</strong> </p>

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

<p><strong>DataConfig:</strong></p>

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

<p><strong>UserRepositoty:</strong></p>

<pre><code>&gt; public interface UserRepository extends JpaRepository&lt;User, Long&gt; {
&gt;     User findByUsername(String username); }
</code></pre>

<p><strong>UserController:</strong></p>

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

<p><strong>Jsp:</strong></p>

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

<p><strong>Error, then add users:</strong></p>

<blockquote>
  <p>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)</p>
</blockquote>

<p><strong>What could be a reason for this execption??</strong></p>