当前位置: 首页 > 知识库问答 >
问题:

TransientPropertyValueException:对象引用未保存的瞬态实例-在刷新之前保存瞬态实例:

强烨
2023-03-14
@Entity
@Table(name="tbl_name")
public class Test extends BaseEntity {

    @OneToOne( fetch = FetchType.LAZY)
    @JoinColumn(name = "ALL_ORG_MST_SECTION_ID",nullable = true)
    private AllOrgMst allOrgMstSection;

    @OneToOne(fetch = FetchType.LAZY )
    @JoinColumn(name = "ALL_ORG_MST_SUB_SECTION_ID",nullable = true)
    private AllOrgMst allOrgMstSubSection;


    
}
{
   "allOrgMstSection": {
        "id": 23
    },
    "allOrgMstSubSection": {
        "id": null
    }
}
  @Autowired
    private TestRepository testRepository;

    @Override
    public Test save2(Test entity) {
        return testRepository.save(entity);
    }

在baseEntity中具有Id

共有1个答案

麹繁
2023-03-14

从您提供的日志和模型中可以清楚地看出,您试图保存一个非托管对象,该对象具有ID

解决方案是在保存之前,先对瞬态对象进行管理(这些对象已经在数据库中)。

这里

"allOrgMstSection": {
        "id": 23
    },
java prettyprint-override">public Test save(Test test) {
    if(test.getAllOrgMstSection() != null && test.getAllOrgMstSection().getId() != null) {
        Long id = test.getAllOrgMstSection().getId();        
        test.setAllOrgMstSection(allOrgMstSectionRepository.getOne(id));
    }

    if(test.getAllOrgMstSubSection() != null && test.getAllOrgMstSubSection().getId() != null ) {
        Long id = test.getAllOrgMstSubSection().getId();
        test.setAllOrgMstSubSection(allOrgMstSubSectionRepository.getOne(id));
    }
    return testRepository.save(test);
}
if(test.getAllOrgMstSection() != null && test.getAllOrgMstSection().getId() != null) {
     AllOrgMstSection updatedAllOrgMsgSection = test.getAllOrgMstSection();

     Long id = test.getAllOrgMstSection().getId();
     AllOrgMstSection existingAllOrgMstSection = allOrgMstSectionRepository.findById(id);
     
     BeanUtils.copyProperties(updatedAllOrgMsgSection, existingAllOrgMstSection /*pass property names you don't want to update*/);
     test.setAllOrgMstSection(existingAllOrgMstSection);
}
 类似资料: