mapstruct将id映射到对象

时间:2018-02-21 20:43:33

标签: java mapstruct

我有一个对象学校,有一个对象人,人已经保存在数据库中,当我保存一个学校对象时,我给它一个人身份

所以在班级学校我有一个Person类型的属性人,而在SchoolDTO我有一个Long类型的属性personId

 @Mapper(componentModel = "spring", uses = { PersonMapper.class }) 
 public interface SchoolMapper extends EntityMapper<SchoolDTO, School>{ 

  @Mapping(source = "personId", target = "person") 
  School toEntity(SchoolDTO schoolDTO); 
 } 

 School school = schoolMapper.toEntity(schoolDTO); 
 log.info(school.getPerson()); 


public interface EntityMapper <D, E> {

 E toEntity(D dto);

 D toDto(E entity);

 List <E> toEntity(List<D> dtoList);

 List <D> toDto(List<E> entityList);
}


@Mapper(componentModel = "spring", uses = {})
public interface PersonMapper extends EntityMapper<PersonDTO, Person> {

  default Person fromId(Long id) {
   if (id == null) {
     return null;
   }
   Person person= new Person();
   person.setId(id);
   return person;
  }
}

这里的问题,当我显示这个人时,它会向我显示带有值的id和另一个属性null

2 个答案:

答案 0 :(得分:3)

仅在设置了ID值的情况下显示Person的原因是因为fromId方法创建了一个空Person并仅设置了ID。

我认为你想从数据库中获取Person

要实现这一点,您只需告诉MapStruct使用服务,或者您可以将其注入映射器并执行提取。

如果您有以下服务:

public interface PersonService {

    Person findById(Long id);
}

你的映射器:

 @Mapper(componentModel = "spring", uses = { PersonService.class }) 
 public interface SchoolMapper extends EntityMapper<SchoolDTO, School>{ 

  @Mapping(source = "personId", target = "person") 
  School toEntity(SchoolDTO schoolDTO); 
 } 

答案 1 :(得分:3)

我们可以通过引入一个 ReferenceMapper 来概括前面的答案,如下所示:

@Component
public class ReferenceMapper {

    @PersistenceContext
    private EntityManager entityManager;

    @ObjectFactory
    public <T> T map(@NonNull final Long id,  @TargetType Class<T> type) {
        return entityManager.getReference(type, id);
    }
}

那么,PersonMapper 将是:

@Mapper(componentModel = "spring", uses = {ReferenceMapper.class})
public interface PersonMapper {

    Person toEntity(Long id);
}

最后是 SchoolMapper:

@Mapper(componentModel = "spring",uses = {PersonMapper.class})
public interface SchoolMapper {

  @Mapping(source = "personId", target = "person") 
  School toEntity(SchoolDTO schoolDTO); 
}

生成的源将是:

@Override
    public School toEntity(InDto dto) {
        if ( dto == null ) {
            return null;
        }

        School school = new School();

        school.setPerson( personMapper.toEntity( dto.getPersonId() ) );
        // other setters

        return school;
    }