当前位置: 首页 > 知识库问答 >
问题:

org.hibernate.PersistentObjectException:传递给persist()的未初始化代理

史和泰
2023-03-14

当我尝试在注册期间保存用户对象时,我得到以下错误

用户服务

> @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);
>     } }
> @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;
>     } }
> @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;
>     } }
> public interface UserRepository extends JpaRepository<User, Long> {
>     User findByUsername(String username); }

用户控制器:

> 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>

错误,然后添加用户:

共有1个答案

余弘毅
2023-03-14

尝试在web.xml中从spring添加OpenEntityManagerInViewFilter

<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>
 类似资料:
  • 当试图在web应用程序上创建课程实体实例时,我们遇到以下错误。这是一个JHipster应用程序完整的错误日志,下面是,但主要错误是 更新的代码:

  • 问题内容: 我已经成功用hibernate写了我的第一个主要的孩子例子。几天后,我再次使用它并升级了一些库。不知道我做了什么,但是我再也无法使它运行了。有人可以帮助我找出返回以下错误消息的代码中的错误吗: hibernate映射: 编辑: InvoiceManager.java 发票.java InvoiceItem.java 编辑: 从客户端发送的JSON对象: 编辑: 一些详细信息: 我试图通

  • JPA和Hibernate的新手,所以请耐心等待,因为我试图绘制一整张图片。所以我有两个具有双向关系的Java对象。员工类是拥有类,部门类是关系的反面。一个部门可以有许多员工,一个员工只能有一个部门。我分配了employee_id作为员工实体的主键,department_id作为部门实体的主键。我还想在员工类中使用department_id作为外键。 员工类 部门类 我用来生成两个对象并将它们保存

  • 我是Hibernate的新手,我需要帮助。 我有一个名为Kasa的表,它有3个属性-id、address和account\u id。在我的表中有12行。我想使用Hibernate对此进行映射,并使用Java添加新的映射,所以我这样做了: 我也有能手和二传手,但不需要复制。 现在我想在我的数据库中添加新行,如下所示: 我得到这样的错误:javax.persistence.PeristenceExce

  • 我有两个模型,一个用于存储用户详细信息,使用该Id,我试图将用户位置保存在另一个表中,该表使用用户的相同Id作为主键。 为什么我会出现这个错误?坚持是什么意思?我正在使用MySQL数据库(&I)

  • 问题内容: 我正在创建一个简单的应用程序,只需使用将一行插入到表中(如果表不存在,则创建它)。 我为它的一个可运行示例附加了一些代码。 这是我得到的异常和stacktrace: 这是我的代码: 主班: 和Person类: 这是我的persistence.xml文件 -----------------------编辑-------------------------- – 我只是将提供程序更改为Ec