Can't save Main Object with giving only ID of Nested Object - giving TransientObjectException Many to many relationship is used

54 Views Asked by At

Let me first introduce my whole problem, I have a UserEntity like this

@Entity
public class UserEntity extends IdDescriptionStateMetaEntity {

  //.. other members  

  @ManyToMany
    @JoinTable(
            name = "role_user",
            joinColumns = @JoinColumn(name = "user_id"),
            inverseJoinColumns = @JoinColumn(name = "role_id"))
    private List<RoleEntity> roles;

  // getter and setter
}

and also have RoleEntity

@Entity public class RoleEntity extends IdDescriptionStateMetaEntity { //fields related to role }

now, I always have role with ID 1 in database.

I just want to save UserEntity with giving id of role. as role always be there in database.

@Transactional
    public UserEntity createUser(){

        UserEntity userEntity = new UserEntity();
        
        List<RoleEntity> roleEntities = new ArrayList<>();
        
        RoleEntity roleEntity = new RoleEntity();
        roleEntity.setId("1");
        roleEntities.add(roleEntity);
        userEntity.setRoles(roleEntities);

        userEntity = userRepository.save(userEntity);
        return userEntity;
    }

When the above method calls it gives exception

TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.model.RoleEntity

I Tried giving Cascade.Merge in manytomany annotation, but still getting the same error.

1

There are 1 best solutions below

2
mamJavad On

you can first find roles from DB and set that to userEntity and then save that in DB