0

My goal is to use a generic class for CRUD operations so that I dont need to implement a seperate class for each domain model in my app.

This layer also converts between my DTOs and the domain model.

The get and delete methods work fine. However, how can I implement the save method. In case of a new entity, I need to create a new instance of the generic and map the DTO on it.

/**
 * This class can be extended to use default CRUD features
 *
 * @param <T> domain model
 * @param <V> DTO represenation of domain model
 */
@RequiredArgsConstructor
public abstract class AbstractCrudService<T extends CoreDomain, V extends CoreDTO> implements CrudStrategy<T, V>{
    
    private final JpaRepository<T, Long> repository;
    private final ModelMapper modelMapper;
    private final Class<V> dtoClass;    
    
    @Override
    public List<V> getAll() {
        List<V> list = new ArrayList<>();
        for (T item : repository.findAll()) {
            list.add(modelMapper.map(item, dtoClass));
        };      
        return list;
    }

    @Override
    public V getById(Long id) {
        T entity = getEntity(id);
        return modelMapper.map(entity, dtoClass);
    }

    @Override
    public void delete(Long id) {
        repository.deleteById(id);      
    }


    @Override
    @Transactional
    public void save(V dto) {
        T entity = new T(); /// DOESNT WORK!!!!
        
        // for edit operation, load existing entity from the DB
        if (dto.getId() != null) {
            entity = getEntity(dto.getId());
        }
        
        modelMapper.map(dto, entity);   
    }
    
    @Override
    public T getEntity(Long id) {
        Optional<T> entity = Optional.ofNullable(repository.findById(id)    
                .orElseThrow(() -> new NoSuchElementException(String.format("Entity with id %s not found", id))));
        return entity.get();
    }   
    
}

My Service class looks like this:

@Service
public class Test extends AbstractCrudService<Project, ProjectDTO>{
    
    private final ProjectRepository projectRepository;
    private final ModelMapper modelMapper;
    
    public Test(ProjectRepository projectRepository, ModelMapper modelMapper) {
        super(projectRepository, modelMapper, ProjectDTO.class);
        this.projectRepository = projectRepository;
        this.modelMapper = modelMapper;
    }   
        
}
Martin Wolff
  • 31
  • 1
  • 5
  • Does this answer your question? [Create instance of generic type in Java?](https://stackoverflow.com/questions/75175/create-instance-of-generic-type-in-java) – Iłya Bursov Jul 03 '20 at 18:32

1 Answers1

0

I solved it with following implementation:

    @Override
    @Transactional
    @SuppressWarnings("unchecked")
    public void save(V dto) {

        ParameterizedType paramType = (ParameterizedType) entityClass.getGenericSuperclass();
        T entity = (T) paramType.getActualTypeArguments()[0];

        // for edit operation, load existing entity from the DB
        if (dto.getId() != null) {
            entity = getEntity(dto.getId());
        }

        modelMapper.map(dto, entity);
    }
Martin Wolff
  • 31
  • 1
  • 5