@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;
}
This is the model . when I insert this model one object is null value then show me the error
Post man Object pass
{
"allOrgMstSection": {
"id": 23
},
"allOrgMstSubSection": {
"id": null
}
}
@Autowired
private TestRepository testRepository;
@Override
public Test save2(Test entity) {
return testRepository.save(entity);
}
In baseEntity have the Id
CodePudding user response:
From the log you provided and the model, its clear that you are trying to save an non-managed object, which have id
.
The solution is to before saving, make the transient object managed (Which are already in the db).
Here the
"allOrgMstSection": {
"id": 23
},
portion seems to already present in the database. Grabbing the managed object / proxy object will solve the issue.
The service
layer code should be similar to following
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);
}
Basically what is done, managed the child object (if they are already present in the database) before saving the parent object. If it does not present in the database.
If you need to perform any update on the child object (i.e updating allOrgMstSection
while saving the test
entity) you have to manually copy the properties. In that case, you could use BeanUtils.copyProperties()
The code should be similar to following
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);
}
CodePudding user response:
just simply soled the issue
{
"allOrgMstSection": {
"id": 23
},
"allOrgMstSubSection": null,
}