user1337:
次の方法でベースのサービス・インターフェースがあります:
public interface BaseService {
Dto convertToDto(Entity entity);
List<Dto> convertToDtoList(List<Entity> entityList);
Entity convertToEntity(Dto dto);
List<Entity> convertToEntityList(List<Dto> dtoList);
}
今の方法convertToDtoListとconvertToEntityListは、これらのメソッドは、唯一の基本サービスに一度実施されるためにあるように、他のサービスによって拡張された基本サービスの実装で実装する必要があります。どちらもconvertToDtoListとconvertToEntityListは、それらが異なるエンティティと、それぞれのサービスクラスのDTOタイプを使用している以外は常に同じ実装を持っています。
public List<Dto> convertToDtoList(List<Entity> entityList) {
if (entityList == null)
return null;
List<Dto> dtoList = new ArrayList<Dto>();
Iterator<Entity> it = entityList.iterator();
while (it.hasNext())
dtoList.add(this.convertToDto(it.next()));
return dtoList;
}
public List<Entity> convertToEntityList(List<Dto> dtoList) {
if (dtoList == null)
return null;
List<Entity> entityList = new ArrayList<Entity>();
Iterator<Dto> it = dtoList.iterator();
while (it.hasNext())
entityList.add(this.convertToEntity(it.next()));
return entityList;
}
どのように私は、私はこの基本サービスを拡張されているすべてのサービス・クラスでそれらを使用できるように、それぞれのエンティティとDTOタイプから抽象化する汎用的な方法で、基本サービスでこれらのメソッドを実装することができますか?
oleg.cherednik:
あなたは、インターフェイスおよびテンプレートのデフォルトの実装を使用することができます<>
:
public interface BaseService<D, E> {
D convertToDto(E entity);
E convertToEntity(D dto);
default List<E> convertToEntityList(List<D> dtoList) {
return Optional.ofNullable(dtoList).orElse(Collections.emptyList()).stream()
.map(this::convertToEntity)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
default List<D> convertToDtoList(List<E> entityList) {
return Optional.ofNullable(entityList).orElse(Collections.emptyList()).stream()
.map(this::convertToDto)
.filter(Objects::nonNull)
.collect(Collectors.toList());
}
}
public class DtoEntityBaseService implements BaseService<Dto, Entity> {
@Override
public Dto convertToDto(Entity entity) {}
@Override
public Entity convertToEntity(Dto dto) {}
}
あなたは助けがこれらすべての変換を行うためにという非常に便利なフレームワークを見ることができます。これは、呼び出しをMapsructを