generated from yandex-praktikum/java-filmorate
-
Notifications
You must be signed in to change notification settings - Fork 0
Add database #3
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
Merged
Merged
Add database #3
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
dc001ed
Добавлено создание встроенной БД и размечена архитектура проекта
dendzim d8b1f83
Исправлены контроллеры и сервисы а также добавлены новые
dendzim 06ea5e1
Исправлены контроллеры и сервисы а также добавлены новые
dendzim 6a26a3d
Исправлены контроллеры и сервисы а также добавлены новые
dendzim 979fdc6
Реализован функционал согласно ФЗ
dendzim 4dac193
Реализован функционал согласно ФЗ
dendzim 1ab6fde
Реализован функционал согласно ФЗ и тестам в постман
dendzim 0add97e
Исправлена работа лайков и добавлены интеграционные тесты
dendzim 9b3774a
Исправлена работа лайков и добавлены интеграционные тесты
dendzim 5fce3a0
Исправлен check style
dendzim b5c1c23
Внесены правки согласно замечаниям
dendzim 4a4fe4b
Внесены правки согласно замечаниям
dendzim File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
49 changes: 25 additions & 24 deletions
49
src/main/java/ru/yandex/practicum/filmorate/controller/FilmController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,67 +1,68 @@ | ||
| package ru.yandex.practicum.filmorate.controller; | ||
|
|
||
| import jakarta.validation.Valid; | ||
| import jakarta.validation.constraints.Positive; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.beans.factory.annotation.Autowired; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import ru.yandex.practicum.filmorate.model.Film; | ||
| import ru.yandex.practicum.filmorate.service.FilmService; | ||
| import ru.yandex.practicum.filmorate.storage.FilmStorage; | ||
|
|
||
| import java.util.Collection; | ||
|
|
||
| @Slf4j | ||
| @RestController | ||
| @RequiredArgsConstructor | ||
| @RequestMapping("/films") | ||
| public class FilmController { | ||
|
|
||
| private final FilmStorage inMemoryFilmStorage; | ||
| private final FilmService filmService; | ||
|
|
||
| @Autowired | ||
| public FilmController(FilmStorage inMemoryFilmStorage, FilmService filmService) { | ||
| this.inMemoryFilmStorage = inMemoryFilmStorage; | ||
| this.filmService = filmService; | ||
| } | ||
| private final FilmService service; | ||
|
|
||
| @GetMapping | ||
| public Collection<Film> findAll() { | ||
| log.info("Список фильмов выведен"); | ||
| return inMemoryFilmStorage.findAll(); | ||
| return service.findAll(); | ||
| } | ||
|
|
||
| @GetMapping("/{id}") | ||
| public Film findById(@PathVariable("id") int filmId) { | ||
| log.info("Фильм с id: {} выведен", filmId); | ||
| return inMemoryFilmStorage.findFilmById(filmId); | ||
| public Film findById(@PathVariable @Positive int id) { | ||
| log.info("Фильм с id: {} выведен", id); | ||
| return service.findFilmById(id); | ||
| } | ||
|
|
||
| @GetMapping("/popular") | ||
| public Collection<Film> getPopular(@RequestParam(defaultValue = "10") int count) { | ||
| public Collection<Film> getPopular(@RequestParam(defaultValue = "10") @Positive int count) { | ||
| log.info("Список популярных фильмов выведен"); | ||
| return filmService.getPopular(count); | ||
| return service.getPopular(count); | ||
| } | ||
|
|
||
| @PostMapping | ||
| public Film create(@RequestBody Film film) { | ||
| public Film create(@Valid @RequestBody Film film) { | ||
| log.info("Фильм: {} добавлен в базу", film); | ||
| return inMemoryFilmStorage.create(film); | ||
| return service.create(film); | ||
| } | ||
|
|
||
| @PutMapping | ||
| public Film update(@RequestBody Film newFilm) { | ||
| public Film update(@Valid @RequestBody Film newFilm) { | ||
| log.info("Данные о фильме: {} обновлены", newFilm); | ||
| return inMemoryFilmStorage.update(newFilm); | ||
| return service.update(newFilm); | ||
| } | ||
|
|
||
| @PutMapping("/{id}/like/{userId}") | ||
| public void addLike(@PathVariable int id, @PathVariable int userId) { | ||
| public Film addLike(@Positive @PathVariable int id, @Positive @PathVariable int userId) { | ||
| log.info("Фильму с id: {} поставил лайк пользователь с id: {}", id, userId); | ||
| filmService.addLike(id, userId); | ||
| return service.addLike(id, userId); | ||
| } | ||
|
|
||
| @DeleteMapping("/{id}/like/{userId}") | ||
| public void deleteLike(@PathVariable int id, @PathVariable int userId) { | ||
| public Film deleteLike(@Positive @PathVariable int id, @Positive @PathVariable int userId) { | ||
| log.info("У фильма с id: {} убрал лайк пользователь с id: {}", id, userId); | ||
| filmService.deleteLike(id, userId); | ||
| return service.deleteLike(id, userId); | ||
| } | ||
|
|
||
| @DeleteMapping("/{id}") | ||
| public void remove(@PathVariable @Positive int id) { | ||
| log.info("Фильм с id: {} удален", id); | ||
| service.remove(id); | ||
| } | ||
| } |
34 changes: 34 additions & 0 deletions
34
src/main/java/ru/yandex/practicum/filmorate/controller/GenreController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| package ru.yandex.practicum.filmorate.controller; | ||
|
|
||
| import jakarta.validation.constraints.Positive; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.web.bind.annotation.GetMapping; | ||
| import org.springframework.web.bind.annotation.PathVariable; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
| import ru.yandex.practicum.filmorate.model.Genre; | ||
| import ru.yandex.practicum.filmorate.service.GenreService; | ||
|
|
||
| import java.util.Collection; | ||
|
|
||
| @Slf4j | ||
| @RestController | ||
| @RequiredArgsConstructor | ||
| @RequestMapping("/genres") | ||
| public class GenreController { | ||
|
|
||
| private final GenreService service; | ||
|
|
||
| @GetMapping | ||
| public Collection<Genre> findAll() { | ||
| log.info("Список жанров выведен"); | ||
| return service.findAll(); | ||
| } | ||
|
|
||
| @GetMapping("/{id}") | ||
| public Genre findGenreById(@Positive @PathVariable("id") int id) { | ||
| log.info("Жанр с id: {} выведен", id); | ||
| return service.findGenreById(id); | ||
| } | ||
| } |
34 changes: 34 additions & 0 deletions
34
src/main/java/ru/yandex/practicum/filmorate/controller/RatingController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| package ru.yandex.practicum.filmorate.controller; | ||
|
|
||
| import jakarta.validation.constraints.Positive; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.web.bind.annotation.GetMapping; | ||
| import org.springframework.web.bind.annotation.PathVariable; | ||
| import org.springframework.web.bind.annotation.RequestMapping; | ||
| import org.springframework.web.bind.annotation.RestController; | ||
| import ru.yandex.practicum.filmorate.model.Rating; | ||
| import ru.yandex.practicum.filmorate.service.RatingService; | ||
|
|
||
| import java.util.Collection; | ||
|
|
||
| @Slf4j | ||
| @RestController | ||
| @RequiredArgsConstructor | ||
| @RequestMapping("/mpa") | ||
| public class RatingController { | ||
|
|
||
| private final RatingService service; | ||
|
|
||
| @GetMapping | ||
| public Collection<Rating> findAll() { | ||
| log.info("Список рейтингов выведен"); | ||
| return service.findAll(); | ||
| } | ||
|
|
||
| @GetMapping("/{id}") | ||
| public Rating findRatingById(@Positive @PathVariable("id") int id) { | ||
| log.info("Рейтинг с id: {} выведен", id); | ||
| return service.findRatingById(id); | ||
| } | ||
| } |
47 changes: 25 additions & 22 deletions
47
src/main/java/ru/yandex/practicum/filmorate/controller/UserController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,71 +1,74 @@ | ||
| package ru.yandex.practicum.filmorate.controller; | ||
|
|
||
| import jakarta.validation.Valid; | ||
| import jakarta.validation.constraints.Positive; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.web.bind.annotation.*; | ||
| import ru.yandex.practicum.filmorate.model.User; | ||
| import ru.yandex.practicum.filmorate.service.UserService; | ||
| import ru.yandex.practicum.filmorate.storage.InMemoryUserStorage; | ||
|
|
||
| import java.util.Collection; | ||
|
|
||
| @Slf4j | ||
| @RestController | ||
| @RequiredArgsConstructor | ||
| @RequestMapping("/users") | ||
| public class UserController { | ||
|
|
||
| private final InMemoryUserStorage inMemoryUserStorage; | ||
| private final UserService userService; | ||
|
|
||
| public UserController(InMemoryUserStorage inMemoryUserStorage, UserService userService) { | ||
| this.inMemoryUserStorage = inMemoryUserStorage; | ||
| this.userService = userService; | ||
| } | ||
| private final UserService service; | ||
|
|
||
| @GetMapping | ||
| public Collection<User> findAll() { | ||
| log.info("Список пользователей выведен"); | ||
| return inMemoryUserStorage.findAll(); | ||
| return service.findAll(); | ||
| } | ||
|
|
||
| @GetMapping("/{id}") | ||
| public User findUserById(@PathVariable("id") int userId) { | ||
| log.info("Пользователь с id: {} выведен", userId); | ||
| return inMemoryUserStorage.findUserById(userId); | ||
| public User findUserById(@Positive @PathVariable int id) { | ||
| log.info("Пользователь с id: {} выведен", id); | ||
| return service.findUserById(id); | ||
| } | ||
|
|
||
| @GetMapping("/{id}/friends") | ||
| public Collection<User> findAllFriends(@PathVariable("id") int userId) { | ||
| public Collection<User> findAllFriends(@Positive @PathVariable("id") int userId) { | ||
| log.info("Список друзей пользователя с id: {} выведен", userId); | ||
| return userService.getFriendList(userId); | ||
| return service.getFriendList(userId); | ||
| } | ||
|
|
||
| @GetMapping("/{id}/friends/common/{otherId}") | ||
| public Collection<User> findAllCommonFriends(@PathVariable int id, @PathVariable int otherId) { | ||
| public Collection<User> findAllCommonFriends(@Positive @PathVariable int id, @Positive @PathVariable int otherId) { | ||
| log.info("Список общих друзей пользователей с id: {} и {} выведен", id, otherId); | ||
| return userService.getCommonFriendList(id, otherId); | ||
| return service.getCommonFriendList(id, otherId); | ||
| } | ||
|
|
||
| @PostMapping | ||
| public User create(@RequestBody User user) { | ||
| public User create(@Valid @RequestBody User user) { | ||
| log.info("Пользоввтель: {} создан и добавлен", user); | ||
| return inMemoryUserStorage.create(user); | ||
| return service.create(user); | ||
| } | ||
|
|
||
| @PutMapping | ||
| public User update(@RequestBody User newUser) { | ||
| public User update(@Valid @RequestBody User newUser) { | ||
| log.info("Данные о пользователе: {} обновлены", newUser); | ||
| return inMemoryUserStorage.update(newUser); | ||
| return service.update(newUser); | ||
| } | ||
|
|
||
| @PutMapping("/{id}/friends/{friendId}") | ||
| public void addFriend(@PathVariable("id") int userId, @PathVariable int friendId) { | ||
| log.info("Пользователь с id: {} добавил пользователя с id: {} в друзья", userId, friendId); | ||
| userService.addFriend(userId, friendId); | ||
| service.addFriend(userId, friendId); | ||
| } | ||
|
|
||
| @DeleteMapping("/{id}/friends/{friendId}") | ||
| public void deleteFriend(@PathVariable("id") int userId, @PathVariable int friendId) { | ||
| log.info("Пользователь с id: {} удалил пользователя с id: {} из друзей", userId, friendId); | ||
| userService.deleteFriend(userId, friendId); | ||
| service.deleteFriend(userId, friendId); | ||
| } | ||
|
|
||
| @DeleteMapping("/{id}") | ||
| public void remove(@Positive @PathVariable int id) { | ||
| log.info("Пользователь с id: {} удален", id); | ||
| service.remove(id); | ||
| } | ||
| } |
69 changes: 69 additions & 0 deletions
69
src/main/java/ru/yandex/practicum/filmorate/dao/BaseDao.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,69 @@ | ||
| package ru.yandex.practicum.filmorate.dao; | ||
|
|
||
| import org.springframework.jdbc.core.JdbcTemplate; | ||
| import org.springframework.jdbc.core.RowMapper; | ||
| import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; | ||
| import org.springframework.jdbc.support.GeneratedKeyHolder; | ||
| import ru.yandex.practicum.filmorate.exception.InternalServerException; | ||
|
|
||
| import java.sql.PreparedStatement; | ||
| import java.sql.Statement; | ||
| import java.util.List; | ||
|
|
||
| public abstract class BaseDao<T> { | ||
| protected final JdbcTemplate jdbc; | ||
| protected final NamedParameterJdbcTemplate namedJdbc; | ||
| protected final RowMapper<T> mapper; | ||
|
|
||
| public BaseDao(JdbcTemplate jdbc, RowMapper<T> mapper) { | ||
| this.jdbc = jdbc; | ||
| this.namedJdbc = new NamedParameterJdbcTemplate(jdbc); | ||
| this.mapper = mapper; | ||
| } | ||
|
|
||
| protected T get(String query, Object... params) { | ||
| return jdbc.queryForObject(query, mapper, params); | ||
| } | ||
|
|
||
| public List<T> getAll(String query, Object... params) { | ||
| return jdbc.query(query, mapper, params); | ||
| } | ||
|
|
||
| public void delete(String query, Integer id) { | ||
| jdbc.update(query, id); | ||
| } | ||
|
|
||
| public void update(String query, Object...params) { | ||
| int rowsUpdated = jdbc.update(query, params); | ||
| if (rowsUpdated == 0) { | ||
| try { | ||
| throw new InternalServerException("Не удалось обновить данные"); | ||
| } catch (InternalServerException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| public int insert(String query, Object... params) { | ||
| GeneratedKeyHolder keyHolder = new GeneratedKeyHolder(); | ||
| jdbc.update(connection -> { | ||
| PreparedStatement ps = connection | ||
| .prepareStatement(query, Statement.RETURN_GENERATED_KEYS); | ||
| for (int idx = 0; idx < params.length; idx++) { | ||
| ps.setObject(idx + 1, params[idx]); | ||
| } | ||
| return ps; }, keyHolder); | ||
|
|
||
| Integer id = keyHolder.getKeyAs(Integer.class); | ||
|
|
||
| if (id != null) { | ||
| return id; | ||
| } else { | ||
| try { | ||
| throw new InternalServerException("Не удалось сохранить данные"); | ||
| } catch (InternalServerException e) { | ||
| throw new RuntimeException(e); | ||
| } | ||
| } | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Отлично, что сделал базовый абстрактный класс,
@Repositoryлишний на нем, т.к. экземпляр не будет никогда создаваться.