jeudi 23 novembre 2017

Which is best layer to place mapper code, service layer or controller layer?

I want to ask about Architectural pattern. I write two snippet code to demo what i ask.

The first way is:

//a method on controller layer (in spring framework)
@RequestMapping(...)
public ShopDTO findShop(final Long shopId){
    Shop shop = shopService.getShopById(shopId);
    ShopDTO shopDTO = shopMapper.toShopDTO(shop);
    return shopDTO;
}

//A method on service layer
@Transactional
public Shop getShopById(final Long shopId){
    //some code to find an entity by id
}

* Note: the code what maps from shop entity to shopDTO in controller layer.

The second way is:

//a method on controller layer (in spring framework)
@RequestMapping(...)
public ShopDTO findShop(final Long shopId){
    ShopDTO shopDTO = shopService.getShopById(shopId);
    return shopDTO;
}

//A method on service layer
@Transactional
public ShopDTO getShopById(final Long shopId){
    Shop shop = shopRepository.findById(shopId);
    ShopDTO shopDTO = shopMapper.toShopDTO(shop);
    return shopDTO;
}

* Note: the code what maps from shop entity to shopDTO in service layer.

My question is: Which is the best practice. And can you tell me why ?

By the side, what is logic should place on controller layer? What is logic should place on service layer?

Thanks.

Aucun commentaire:

Enregistrer un commentaire