Conversation
Code Coverage
|
| this.tgChats = new HashSet<>(); | ||
| } | ||
|
|
||
| public Link toDto() { |
There was a problem hiding this comment.
Для маппинга в дто и обратно принято использовать отдельные классы мапперы.
Хранить логическую часть преобразования в дто в самой сущности не очень здорово.
Когда есть маппер - он ответственен и тут все понятно, а сейчас нарушается Single Responsibility.
Чтобы не писать маппер вручную есть библиотеки MapStruct и ModelMapper. Рекомендую=)
There was a problem hiding this comment.
@repository противоречит условию задания 3
There was a problem hiding this comment.
Почему противоречит, в условии не запрещено использование @repository, укажите пожалуйста где это написано, возможно, я не до конца понял условие. Я нашел лишь запрет на использование @Service/@component.
There was a problem hiding this comment.
@repository - мета-аннотация, по существу тот же @component.
Не забудьте удалить любые аннотации связанные с жизненным циклом (@Service/@component) с базовых интерфейсов и имплементаций, создание имплементаций должно происходить в конфигурационном файле при помощи @bean
С учетом вышесказанного, странно ограничиваться только приведенными примерами аннотаций в скобках.
There was a problem hiding this comment.
equals, hashcode, tostring везде будут просто от Object?
| public LinkResponse addTrackingLink(URL link, Long chatId) { | ||
| TgChatEntity chat = chatRepository.findById(chatId).orElseThrow(() -> new ChatNotFoundException(chatId)); | ||
| String host = link.getHost(); | ||
| String domain = host.replaceAll("^(www\\.)?|\\.com$", ""); | ||
| InfoSupplier infoSupplier = infoSuppliers.getSupplierByTypeHost(domain); | ||
| if (infoSupplier == null || !infoSupplier.isSupported(link)) { | ||
| throw new LinkIsNotSupportedException(link); | ||
| } | ||
|
|
||
| LinkInfo linkInfo = infoSupplier.fetchInfo(link); | ||
| if (linkInfo == null) { | ||
| throw new LinkIsNotSupportedException(link); | ||
| } | ||
|
|
||
| Optional<LinkEntity> linkOptional; | ||
| OffsetDateTime lastUpdate = OffsetDateTime.now(); | ||
| if (!linkInfo.events().isEmpty()) { | ||
| lastUpdate = linkInfo.events().getFirst().lastUpdate(); | ||
| } | ||
|
|
||
| LinkEntity linkEntity; | ||
| linkOptional = linkRepository.findByUrl(String.valueOf(linkInfo.url())); | ||
| if (linkOptional.isPresent()) { | ||
| linkEntity = linkOptional.get(); | ||
| linkEntity.setLastUpdate(lastUpdate); | ||
| linkEntity.setLastCheck(OffsetDateTime.now()); | ||
| linkEntity.setMetaInfo(linkInfo.metaInfo()); | ||
| chat.addLink(linkEntity); | ||
| return new LinkResponse(linkEntity.getId(), link); | ||
| } | ||
| linkEntity = new LinkEntity( | ||
| String.valueOf(link), | ||
| lastUpdate, | ||
| OffsetDateTime.now(), | ||
| linkInfo.metaInfo() | ||
| ); | ||
| chat.addLink(linkEntity); | ||
| return new LinkResponse(linkEntity.getId(), link); | ||
| } |
There was a problem hiding this comment.
тяжеловато, давай разобьем на несколько методов?
| @Override | ||
| @Transactional | ||
| public void deleteChat(Long tgChatId) { | ||
| TgChatEntity tgChatEntity = | ||
| chatRepository.findById(tgChatId).orElseThrow(() -> new ChatNotFoundException(tgChatId)); | ||
|
|
||
| for (LinkEntity link : tgChatEntity.getLinks()) { | ||
| tgChatEntity.removeLink(link); | ||
| if (link.getTgChats().isEmpty()) { | ||
| linkRepository.delete(link); | ||
| } | ||
| } | ||
| chatRepository.delete(tgChatEntity); | ||
| } |
There was a problem hiding this comment.
На примере этого метода.
В зависимостях 2 репозитория :
private final JpaChatRepository chatRepository;
private final JpaLinkRepository linkRepository;
и далее в другом сервисе тоже.
Может получится лучше, если мы попробуем оставить 1 соответствующий репозиторий в зависимостях, а вместо других использовать сервисы. Чтобы сервисы были ответственны за обращение к своему репозиторию, любую логику, выброс и обработку ошибок. И не придется дублировать код работы с каждым репо в каждом методе.
There was a problem hiding this comment.
Один сервис зависит от другого, и я не могу создать бины в таком случае, поэтому я оставлю как есть
| jpa: | ||
| hibernate: | ||
| ddl-auto: validate | ||
| open-in-view: false |
There was a problem hiding this comment.
еще можно добавить для удобства
show-sql: true
чтобы видеть какие sql запросы генерит hiber
No description provided.