Issue
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
Solution
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.
Answered By - Pallav Kabra
Answer Checked By - Robin (JavaFixing Admin)