在SpringBoot 2.0.4应用程序中刷新之前保存临时实例 [英] save the transient instance before flushing in SpringBoot 2.0.4 app

查看:175
本文介绍了在SpringBoot 2.0.4应用程序中刷新之前保存临时实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的SpringBoot 2.0.4.RELEASE应用程序.使用Spring Initializer,JPA,嵌入式Tomcat,Thymeleaf模板引擎并将其打包为可执行JAR文件.

I have a basic SpringBoot 2.0.4.RELEASE app. using Spring Initializer, JPA, embedded Tomcat, Thymeleaf template engine, and package as an executable JAR file.

我有这种方法:

@Transactional
    public User createUser(User user, Set<UserRole> userRoles) {

        User localUser = userRepository.findByEmail(user.getEmail());

        if (localUser != null) {
            LOG.info("User with username {} and email {} already exist. Nothing will be done. ",
                    user.getUsername(), user.getEmail());
        } else {

            String encryptedPassword = passwordEncoder.encode(user.getPassword());
            user.setPassword(encryptedPassword);


            for (UserRole ur : userRoles) {

                LOG.info("Saving role " + ur);

                roleRepository.save(ur.getRole());
            }

            user.getUserRoles().addAll(userRoles);

            localUser = userRepository.save(user);

        }

        return localUser;
    }

但是当我创建一个用户时:

but when I create a User:

 User user = new User();



        Set<UserRole> userRoles = new HashSet<>();
        userRoles.add(new UserRole(user, new Role(RolesEnum.ADMIN)));
        userService.createUser(user, userRoles);

我收到此错误:

object references an unsaved transient instance - save the transient instance before flushing : com.tdk.backend.persistence.domain.backend.UserRole.role -> com.tdk.backend.persistence.domain.backend.Role

推荐答案

包含 cascade ="all" (如果使用xml)或 cascade = CascadeType.ALL (如果使用注释) 在您的收藏夹映射上.

Include cascade="all" (if using xml) or cascade=CascadeType.ALL (if using annotations) on your collection mapping.

因为您的实体中有一个集合,并且该集合具有数据库中不存在的一项或多项.使用上述选项,您告诉hibernate在保存其父级时将其保存到数据库中.

Because you have a collection in your entity, and that collection has one or more items which are not present in the database. Using above option you tell hibernate to save them to the database when saving their parent.

这篇关于在SpringBoot 2.0.4应用程序中刷新之前保存临时实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆