hibernate 无法在仅给出嵌套对象ID的情况下保存主对象-给出使用多对多关系的TransientObjectException

sr4lhrrt  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(97)

让我先介绍一下我的整个问题,我有一个这样的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,但仍然得到同样的错误。

atmip9wb

atmip9wb1#

您可以先从数据库中查找角色并将其设置为userEntity,然后将其保存到数据库中

相关问题