我创建了这种代码结构。它越来越不通用了。
我搜索更多通用代码。
我的所有控制器都应该有一个save,get,getById
如何拥有更通用的控制器? 如何传递服务对象,我需要传递
对于其他层,如果你认为这可能更通用......不要犹豫不决
@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);
}
....
}
答案 0 :(得分:0)
我建议你看一下Spring Data Rest,它可以帮助你更有效地推广你的代码。