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.
you can first find roles from DB and set that to userEntity and then save that in DB