Skip to content

Add database#3

Merged
dendzim merged 12 commits intomainfrom
add-database
Dec 25, 2025
Merged

Add database#3
dendzim merged 12 commits intomainfrom
add-database

Conversation

@dendzim
Copy link
Owner

@dendzim dendzim commented Dec 19, 2025

QuickDBD-FilmorateDB Пришлось пересоздать ветку и залить по новой схему БД с промежуточной peer-to-peer проверки. В самом проекте в БД нет поля статус в таблице User_friends и переименованы некоторые поля из-за синтаксиса тестов постмана, остальное осталось неизменным. По ФЗ12 реализован функционал ФЗ12 Добавлена H2 БД которая записывается в файл в проекте и в память для интеграционных тестов соответственно. Добавлены интеграционные тесты. В проекте осталось два рудиментарных класса реализовывающих хранение данных в памяти. В pom файл добавлен check style плагин.

@VadimZharkov
Copy link

QuickDBD-FilmorateDB Пришлось пересоздать ветку и залить по новой схему БД с промежуточной peer-to-peer проверки. В самом проекте в БД нет поля статус в таблице User_friends и переименованы некоторые поля из-за синтаксиса тестов постмана, остальное осталось неизменным. По ФЗ12 реализован функционал ФЗ12 Добавлена H2 БД которая записывается в файл в проекте и в память для интеграционных тестов соответственно. Добавлены интеграционные тесты. В проекте осталось два рудиментарных класса реализовывающих хранение данных в памяти. В pom файл добавлен check style плагин.

Было бы лучше привести в соответствие текущей схемы БД

private final FilmService filmService;
private final FilmService service;

@Autowired
Copy link

@VadimZharkov VadimZharkov Dec 20, 2025

Choose a reason for hiding this comment

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

@Autowired перед конструктором можно не писать.
Да и весь конструктор с рутинным кодом можно не писать, если воспользоваться библиотекой lombok. Советую ее изучить и применять.
https://habr.com/ru/companies/piter/articles/676394/

Choose a reason for hiding this comment

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

InMemory реализации из проекта нужно убрать, больше не понадобятся.

Choose a reason for hiding this comment

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

InMemory реализации из проекта нужно убрать, больше не понадобятся.

@ExceptionHandler
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ErrorResponse handleValidationException(final ValidationException e) {
return new ErrorResponse(e.getMessage());

Choose a reason for hiding this comment

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

Лучше добавить логирование ошибок log.error(...), это позволит легче с ними разбираться.

}

public static final Comparator<Film> comparator = Comparator.comparingInt(Film::getRating).reversed();
private void validateFilm(Film film) {

Choose a reason for hiding this comment

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

Для валидации можно также использовать аннотации валидации на полях классов (@NotNull, @Size и т.д.) и параметрах методов (@Valid, @Validated). Советую применить, т.к. в дальнейшем этот подход будет использоваться часто.

import java.util.List;

@Repository
public abstract class BaseDao<T> {

Choose a reason for hiding this comment

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

Отлично, что сделал базовый абстрактный класс, @Repository лишний на нем, т.к. экземпляр не будет никогда создаваться.

}
private Rating mpa;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Integer likes = 0;

Choose a reason for hiding this comment

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

Можно не хранить в поле и соответственно обновлять и удалять кол-во лайков, а рассчитывать с помощью SQL в getPopular


@Override
public Film create(Film film) {
if (ratingStorage.findRatingById(film.getMpa().getId()).isEmpty()) {

Choose a reason for hiding this comment

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

Проверки на существование рейтинга и жанров можно не делать, т.к. в схеме БД сделаны внешние ключи и выбросится исключение, если вставляемых рейтингов и жанров не будет в БД

.map(genre -> new Object[]{filmId, genre.getId()})
.toList();

jdbc.batchUpdate(ADD_GENRE_TO_FILM_QUERY, batchArgs);

Choose a reason for hiding this comment

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

Отлично, что используешь batchUpdate

Copy link

@VadimZharkov VadimZharkov left a comment

Choose a reason for hiding this comment

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

Хорошая работа в целом, можно улучшить.

@dendzim
Copy link
Owner Author

dendzim commented Dec 23, 2025

Внес правки согласно замечаниям:
-Вложил диаграмму БД с актуальными данными проекта
-Убрал InMemory реализации и их тесты
-Убрал поле с лайками из модели Film
-Переделал валидацию на валидацию аннотациями
-Убрал лишние проверки и методы старой валидации
-Добавил кастомную валидацию Даты выпуска фильма
-Спрятал конструкторы контроллеров под аннтоации


@Getter
public class ErrorResponse {
String error;

Choose a reason for hiding this comment

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

private final

);

CREATE TABLE IF NOT EXISTS films_genres (
film_id INTEGER,

Choose a reason for hiding this comment

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

NOT NULL


CREATE TABLE IF NOT EXISTS films_genres (
film_id INTEGER,
genre_id INTEGER,

Choose a reason for hiding this comment

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

NOT NULL

Copy link

@VadimZharkov VadimZharkov left a comment

Choose a reason for hiding this comment

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

Доработки увидел, все хорошо. Нужно еще пару моментов поправить.

@dendzim dendzim merged commit 87113ce into main Dec 25, 2025
2 checks passed
@dendzim dendzim deleted the add-database branch December 25, 2025 17:27
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.

2 participants

Comments