I have an entity with some nested entities like this
public class MyEntity { @ManyToOne @JoinColumn(name="FK_ENTITY2") private Entity2 fkEntity2; @ManyToOne @JoinColumn(name="FK_ENTITY3") private Entity3 fkEntity3; }
with entity2 and entity3 like this:
public class Entity2/3{ @Id private Long id; @Column(name = "code") private String code; @Column(name = "desc") private String desc; //getter and setter etc }
Both Entity2
and Entity3
have values stored in the database so when I’m doing an insert on MyEntity
, I’m doing this:
@Transactional @Service public MyService { //idFromController and otherIdFromController refers to existent records in the database public MyDto save(Long idFromController, Long otherIdFromController){ Entity2 entity2 = new Entity2(); entity2.setId(idFromController); Entity3 entity3 = new Entity3(); entity3.setId(otherIdFromController); MyEntity newMyEntity = new MyEntity(); newMyEntity.setEntity2(entity2); newMyEntity.setEntity3(entity3); MyEntity result = myEntityRepository.saveAndFlush(newMyEntity); return getDto(result); } }
it works fine, the data are stored correctly in the DB with the correct foreign keys BUT… After insert I want to build a DTO which contains id, code and desc from the nested entities so something like this:
private MyDto getDto(MyEntity result){ MyDto dto = new MyDto(); dto.setId2(result.getEntity2().getId()); dto.setCode2(result.getEntity2().getCode()); dto.setDesc2(result.getEntity2().getDesc()); dto.setId3(result.getEntity3().getId()); dto.setCode3(result.getEntity3().getCode()); dto.setDesc3(result.getEntity3().getDesc()); }
Here is the problem, I only got the id fields and null on code and description.
When I call getDto()
in a search it works and every field has the correct values, so it is something related to the insert transaction? how could I solve this?
Advertisement
Answer
When you create the DTO, the (existing) entities are not attached to the persistence context, so the corresponding data has not been loaded from the DB and cannot be copied to the DTO.
One option would be to load the entities e.g. via ‘myRepository.findById…’ and associate the returned (managed) entities.