Skip to content

Conversation

@Slavakorgg
Copy link
Owner

No description provided.

Copy link

@EugeneLenkevich EugeneLenkevich left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Привет, Вячеслав! Спасибо за PR.

Отличная работа! :)
Есть совсем небольшие пометки, посмотри комментарии ниже, пожалуйста

В первую очередь

  • раз у нас есть для сервисов интерфейс+реализация, то инжектить стоит через интерфейс, именно этого будут все ожидать. Ну или убрать вовсе интерфейсы и инжектить реализации, но тогда названия пусть будут без Impl
  • посмотри еще запросы в цикле - это потенциальные проблемы производительности :)


private static final Logger log = LoggerFactory.getLogger(FilmController.class);
private final FilmService filmService;
private final FilmServiceImpl filmService;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FilmServiceImpl

Раз у нас есть интерфейс, то тут стоит именно его и инжектить, а не реализацию. В других местах аналогично :)


for (Film film : films) {

getGenre(film);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Запрос в БД - дорогая операция, их лучше минимизировать, а тут же в цикле идут запросы для каждого элемента. Это не особо эффективно особенно если у нас будет много записей в БД.
По сути дела мы делаем запрос
select * from

where id = :id

можно заменить на

select * from

where id in (:ids)

где ids - список идентификаторов :)

Так будет гораздо эффективней с точки зрения производительности

for (Genre genre : genres) {
if (!duplicateGenres.contains(genre)) {
params.addValue("genre_id", genre.getId());
jdbc.update("INSERT INTO FILM_GENRES (FILM_ID, GENRE_ID) VALUES(:film_id, :genre_id);", params, keyHolder);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вот тут тоже цикле запросы, причем инсерты, что еще дороже чем селект в том же цикле. А что если склеить все запросы в одну строку

  • как набор операторов через ; insert into t1() values (...); insert into t1() values (...); ...
  • как один оператор, примерно вот так insert into t1() values (...), (...),...(...);


@Override
public Genre getGenreById(int id) throws DataNotFoundException {
if (id > 6) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

id > 6

А это уже "магия", а точно надо ограничивать идентификатор?


@Override
public Mpa getById(int id) throws DataNotFoundException {
if (id > 5) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

id > 5

Магия, аналогично. Это выглядит как какой то неочевидный хак, никто потом не разберется почему так, лучше такого избегать, это неочевидно и совершенно неожиданно :)

public class FilmControllerTest {

@Autowired
/* @Autowired

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше, конечно, тест не комментить а попробовать починить. Ну и сразу - контроллер инжектить не надо, надо запрос отправить :)

Copy link

@EugeneLenkevich EugeneLenkevich left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Давай не будем, все таки, из таблицы БД все что есть тащить, отметил комментарием, посмотри. пожалуйста

@Override
public Genre getGenreById(int id) throws DataNotFoundException {
if (id > 6) {
if (id > jdbcGenreRepository.getAll().size()) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

jdbcGenreRepository.getAll().size()

Это сурово, мы вытаскиваем все записи из таблицы чтобы проверить id, а если записей вдруг станет много, у нас кончится память, в общем, там лучше не делать

Copy link

@EugeneLenkevich EugeneLenkevich left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Теперь все отлично, спасибо :)

@Slavakorgg Slavakorgg merged commit 0b5df7f into main May 5, 2025
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants