让我先介绍一下我的整个问题,我有一个这样的UserEntity
@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
}
也有RoleEntity@Entity public class RoleEntity extends IdDescriptionStateMetaEntity { //fields related to role }
现在,我在数据库中总是有ID为1的角色。
我只想保存UserEntity,并给出角色的ID。作为角色始终存在于数据库中。
@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;
}
当上面的方法调用时,它给出异常TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.model.RoleEntity
我试着给Cascade.Merge in manytomany annotation,但仍然得到同样的错误。
1条答案
按热度按时间atmip9wb1#
您可以先从数据库中查找角色并将其设置为userEntity,然后将其保存到数据库中