@Override public void add( NewsDTO newsDTO ) { try { News news; try { // Updates news = detail(newsDTO.getUsername(), newsDTO.getTitle()); news.setContent(newsDTO.getContent()); } catch (Exception e) { // What's New news = new News(); news.setTitle(newsDTO.getTitle()); news.setContent(newsDTO.getContent()); news.setUsername(newsDTO.getUsername()); } this.saveOrUpdate(news); } catch (Exception e) { log.info(e.getMessage()); throw new RequestException(ResponseCode.SQL_FAIL); } } @Override public News detail( String username, String title ) { try { return this.getOne(Wrappers.<News>lambdaQuery().eq(News::getUsername, username).eq(News::getTitle, title)); } catch (RuntimeException e) { throw new RequestException(ResponseCode.TOO_MANY_RESULTS); } }
This allows for additions and updates based on the business primary key after finding the record to be modified.Finally, unified additions or modifications are achieved through IService's saveOrUpdate.But I always find it not elegant to write new records in a catch.It's not good to implement a detail method, is there a better one?
// The following is added through insert on the BaseMapper interface, and the update implementation is modified according to the business primary key @Override public void add( NewsDTO newsDTO ) { try { // Update situation: Update one first, if you can update successfully, it means update situation, otherwise it is new situation boolean flag = new LambdaUpdateChainWrapper<News>(newsMapper) .eq(News::getTitle, newsDTO.getTitle()) .eq(News::getUsername, newsDTO.getUsername()) .set(News::getContent, newsDTO.getContent()).update(); log.info("flag is "+flag); // What's new: If you can't update your success if (!flag) { News news = new News(); news.setTitle(newsDTO.getTitle()); news.setContent(newsDTO.getContent()); news.setUsername(newsDTO.getUsername()); newsMapper.insert(news); } } catch (Exception e) { throw new RequestException(ResponseCode.SQL_FAIL); } }