Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Функциональность «Общие фильмы». #13

Closed
wants to merge 198 commits into from

Conversation

Kazantsevyury
Copy link
Collaborator

Добавлен новый метод getCommonFilms в класс FilmServiceImpl и соответствующий обработчик запросов в FilmController для вывода списка общих фильмов двух пользователей с сортировкой по популярности. Основные моменты изменений:

В FilmServiceImpl реализован метод getCommonFilms, который:

Использует filmLikeStorage.findLikedFilmsByUser для получения фильмов, лайкнутых каждым из пользователей.
Находит пересечение этих списков для определения общих фильмов.
Сортирует общие фильмы по количеству лайков с помощью Comparator.comparingLong(FilmDto::getLikes).reversed().
В FilmController добавлен обработчик GET-запросов на путь '/common', принимающий параметры userId и friendId.

vvbakhanovich and others added 27 commits February 1, 2024 16:25
Добавление режиссеров в фильмы
…улярности.

Добавлен новый метод getCommonFilms в класс FilmServiceImpl и соответствующий обработчик запросов в FilmController для вывода списка общих фильмов двух пользователей с сортировкой по популярности. Основные моменты изменений:

1. В FilmServiceImpl реализован метод getCommonFilms, который:
   - Использует filmLikeStorage.findLikedFilmsByUser для получения фильмов, лайкнутых каждым из пользователей.
   - Находит пересечение этих списков для определения общих фильмов.
   - Сортирует общие фильмы по количеству лайков  с помощью Comparator.comparingLong(FilmDto::getLikes).reversed().

2. В FilmController добавлен обработчик GET-запросов на путь '/common', принимающий параметры userId и friendId.
…чения информации о фильмах за один запроc
…ava-filmorate into add-common-films

# Conflicts:
#	src/main/java/ru/yandex/practicum/filmorate/dao/FilmLikeStorage.java
#	src/main/java/ru/yandex/practicum/filmorate/dao/FilmStorage.java
#	src/main/java/ru/yandex/practicum/filmorate/dao/impl/FilmDbStorage.java
#	src/main/java/ru/yandex/practicum/filmorate/dao/impl/FilmLikeDbStorage.java
#	src/main/java/ru/yandex/practicum/filmorate/service/FilmService.java
#	src/main/java/ru/yandex/practicum/filmorate/service/impl/FilmServiceImpl.java
#	src/main/resources/schema.sql
#	src/test/java/ru/yandex/practicum/filmorate/storage/ReviewDbStorageTest.java
Comment on lines 204 to 238
private Collection<Film> extractToFilmList(ResultSet rs) throws SQLException, DataAccessException {

final Map<Long, Film> filmIdMap = new LinkedHashMap<>();

while (rs.next()) {

Long filmId = rs.getLong(1);
Film film = filmIdMap.get(filmId);
if (film == null) {
film = Film.builder()
.id(filmId)
.name(rs.getString("title"))
.description(rs.getString("description"))
.releaseDate(rs.getDate("release_date").toLocalDate())
.duration(rs.getInt("duration"))
.mpa(new Mpa(rs.getInt("mpa_id"), rs.getString("rating_name")))
.build();
film.setLikes(rs.getLong("likes"));
filmIdMap.put(filmId, film);
}

final int genre_id = rs.getInt("genre_id");
if (genre_id == 0) {
film.getGenres().addAll(Collections.emptyList());
continue;
}

final Genre genre = new Genre();
genre.setId(genre_id);
genre.setName(rs.getString("genre_name"));
film.getGenres().add(genre);
}

return filmIdMap.values();
}
Copy link
Owner

Choose a reason for hiding this comment

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

Этот метод не используется, его нужно удалить

"GROUP BY f.id, m.rating_name ", ids);

Collection<Film> films = jdbcTemplate.query(sql, this::mapToFilm, filmIds.toArray());
return setGenresForFilms(films);
Copy link
Owner

Choose a reason for hiding this comment

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

Здесь нужно еще прикрепить режиссеров при помощи setDirectorsForFilms

return film;
}

private Collection<Film> extractToFilmList(ResultSet rs) throws SQLException, DataAccessException {
private Collection<Film> extractToFilmList(ResultSet rs) throws SQLException {
Copy link
Owner

Choose a reason for hiding this comment

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

Этот метод больше не используется, его надо удалить

Comment on lines +214 to +229
Object[] idsArray = filmIds.toArray(new Object[0]);

return jdbcTemplate.query(sql, idsArray, new RowMapper<Film>() {
@Override
public Film mapRow(ResultSet rs, int rowNum) throws SQLException {
Film film = new Film();
film.setId(rs.getLong("ID"));
film.setName(rs.getString("TITLE"));
film.setDescription(rs.getString("DESCRIPTION"));
film.setReleaseDate(rs.getDate("RELEASE_DATE").toLocalDate());
film.setDuration(rs.getInt("DURATION"));
film.setMpa(new Mpa(rs.getInt("MPA_ID"), rs.getString("RATING_NAME")));
film.setLikes(rs.getLong("LIKES"));
return film;
}
});
Copy link
Owner

Choose a reason for hiding this comment

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

Насколько я понимаю этот метод ты больше не используешь? Если да, то его стоит удалить)

Comment on lines +164 to +165
Set<Long> userLikedFilmIds = filmLikeStorage.findLikedFilmsByUser(userId);
Set<Long> friendLikedFilmIds = filmLikeStorage.findLikedFilmsByUser(friendId);
Copy link
Owner

Choose a reason for hiding this comment

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

Перед вызовом этих методов лучше проверить есть ли эти пользователи в БД

* @return список DTO фильмов, которые лайкнуты обоими пользователями. .
* Если общих лайкнутых фильмов нет, возвращается пустой список.
*/
@Override
Copy link
Owner

Choose a reason for hiding this comment

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

Так как в методе есть несколько обращений к БД лучше поставить аннотацию @transactional

return Collections.emptyList();
}

Collection<Film> commonFilms = filmStorage.findFilmsByIds(userLikedFilmIds);
Copy link
Owner

Choose a reason for hiding this comment

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

Возвращаются ли фильмы в порядке популярности?

@Kazantsevyury Kazantsevyury deleted the add-common-films branch February 5, 2024 20:19
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