简体   繁体   中英

save the transient instance before flushing in SpringBoot 2.0.4 app

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.

I have this method:

@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);

I got this error:

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

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

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.

This happens when saving an object when Hibernate thinks it needs to save an object that is associated with the one you are saving.

also before saving the Role into database, you are saving the user which is wrong because hibernate session is not aware of that object till that point of time.So to get rid of this error use CascadeType.ALL on mappings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM