I created this structure of code. it's more and less generic.
I search to write more generic code.
all my controller should have a save, get, getById
How to have a more generic controller?, how to pass service object, do i need to pass
for other layer, if you think that could be more generic... don't hesitage
@RequestMapping(value = "/rest")
@RestController
public class CardsRestController extends BaseController {
private final CardsService cardsService;
@Autowired
public CardsRestController(final CardsService cardsService) {
this.CardsService = cardsService;
}
@GetMapping(value = "/cards")
public ResponseEntity<Page<CardsDto>> getCards(Pageable page) {
if (page == null) {
page = getDefaultPageRequest();
}
return new ResponseEntity<>(cardsService.getCards(page), HttpStatus.OK);
}
@GetMapping(value = "/cards/{id}")
public ResponseEntity<CardsDto> getCardsById(@PathVariable("id") Integer id) {
CardsDto Cards = cardsService.getCardsById(id);
return Cards != null
? new ResponseEntity(Cards, HttpStatus.OK)
: new ResponseEntity(HttpStatus.NOT_FOUND);
}
}
public abstract class BaseController {
protected PageRequest getDefaultPageRequest() {
return PageRequest.of(0, 20);
}
}
public interface CardsService {
public void saveCards(CardsDto cardDto);
public Page<CardsDto> customSearch(CardSearch CardSearch, Pageable page);
public Page<CardsDto> getCards(Pageable page);
public CardsDto getCardsById(Integer id);
}
public class CardsServiceImpl extends BaseService<Cards, CardsDto> implements CardsService {
@Autowired
public CardsServiceImpl(CardsRepository cardsRepository) {
super(Cards.class);
this.cardsRepository = cardsRepository;
}
public CardsRepository cardsRepository;
@Override
public void saveCards(CardsDto cardDto) {
save(cardDto);
}
}
public abstract class BaseService<T, R extends BaseDto> {
private JpaRepository<T, Integer> repository;
private final Class< T> clsT;
public BaseService(Class<T> clsT) {
this.clsT = clsT;
}
public Page<R> get(Pageable page, JpaRepository<T, Integer> repository, Function<T, R> convert) {
Page<T> pageR = repository.findAll(page);
List<R> dtos = convertsToDto(pageR.getContent(), convert);
return new PageImpl<>(dtos, page, pageR.getTotalElements());
}
public R getById(Integer id, Function<T, R> convert){
Optional<T> beans = repository.findById(id);
if (beans.isPresent()) {
return convert.apply(beans.get());
}
return null;
}
}
public interface CardsRepository extends JpaRepository<Cards, Integer>, CardsRepositoryCustom {
}
public interface CardsRepositoryCustom {
}
@Repository
public class CardsRepositoryImpl extends SimpleJpaRepository implements CardsRepositoryCustom{
@PersistenceContext
private EntityManager em;
@Autowired
public CardsRepositoryImpl(EntityManager em) {
super(Cards.class, em);
}
....
}