Compare commits

..

2 Commits

Author SHA1 Message Date
parap
4d916bdfe6 fix 2023-04-29 18:01:53 +04:00
parap
901f388780 4 lab first step 2023-04-29 18:00:04 +04:00
16 changed files with 543 additions and 163 deletions

View File

@ -0,0 +1,43 @@
package ru.ip.labs.labs.films.controller;
import org.springframework.web.bind.annotation.*;
import ru.ip.labs.labs.films.dto.ActorDTO;
import ru.ip.labs.labs.films.service.ActorService;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequestMapping("/actors")
public class ActorController {
private final ActorService actorService;
public ActorController(ActorService actorService) {
this.actorService = actorService;
}
@GetMapping("/{id}")
public ActorDTO getActor(@PathVariable Long id) {
return actorService.findActor(id);
}
@GetMapping("")
public List<ActorDTO> getActors() {
return actorService.findAllActors();
}
@PostMapping("")
public ActorDTO createActor(@RequestBody @Valid ActorDTO actor) {
return actorService.addActor(actor.getName(), actor.getSurname());
}
@PatchMapping("")
public ActorDTO updateActor(@PathVariable Long id, @RequestBody @Valid ActorDTO actor) {
return actorService.updateActor(id, actor.getName(), actor.getSurname());
}
@DeleteMapping("/{id}")
public ActorDTO deleteActor(@PathVariable Long id) {
return actorService.deleteActor(id);
}
}

View File

@ -1,56 +1,59 @@
package ru.ip.labs.labs.films.controller; package ru.ip.labs.labs.films.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ip.labs.labs.films.dto.FilmDTO;
import ru.ip.labs.labs.films.models.Film; import ru.ip.labs.labs.films.models.Film;
import ru.ip.labs.labs.films.models.Genre;
import ru.ip.labs.labs.films.service.FilmsService; import ru.ip.labs.labs.films.service.FilmsService;
import javax.validation.Valid;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("/film") @RequestMapping("/films")
public class FilmController { public class FilmController {
private final FilmsService filmService; private final FilmsService filmService;
public FilmController(FilmsService filmService) { public FilmController(FilmsService filmService) {
this.filmService = filmService; this.filmService = filmService;
} }
@GetMapping("/test")
public String test() {
return "Test request";
}
@GetMapping("/{id}") @GetMapping("/{id}")
public Film getFilm(@PathVariable Long id) { public FilmDTO getFilm(@PathVariable Long id) {
return filmService.findFilm(id); return filmService.findFilm(id);
} }
@GetMapping("/") @GetMapping("")
public List<Film> getFilms() { public List<FilmDTO> getFilms() {
return filmService.findAllFilms(); return filmService.findAllFilms();
} }
@PostMapping("/") @PostMapping("")
public Film createFilm(@RequestParam String name) { public FilmDTO createFilm(@RequestBody @Valid FilmDTO film) {
return filmService.addFilm(name); FilmDTO result = filmService.addFilm(film.getName());
return filmService.updateGenres(result.getId(), film.getGenre());
} }
@PatchMapping("/{id}") @PatchMapping("/{id}")
public Film updateFilm(@PathVariable Long id, public FilmDTO updateFilm(@PathVariable Long id,
@RequestParam("firstName") String name) { @RequestBody @Valid FilmDTO film) {
return filmService.updateFilm(id, name); FilmDTO result = filmService.updateFilm(id, film.getName());
return filmService.updateGenres(result.getId(), film.getGenre());
} }
@PatchMapping("/add_genre/{id}") @PatchMapping("/add_genre/{id}")
public Film addGenre(@PathVariable Long id, @RequestParam Long genre_id) { public FilmDTO addGenre(@PathVariable Long id, @RequestParam Long genre_id) {
return filmService.addGenre(id, genre_id); return filmService.addGenre(id, genre_id);
} }
@PatchMapping("/add_actor/{id}")
public FilmDTO addActor(@PathVariable Long id, @RequestParam Long actor_id) {
return filmService.addActor(id, actor_id);
}
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public Film deleteFilm(@PathVariable Long id) { public FilmDTO deleteFilm(@PathVariable Long id) {
return filmService.deleteFilm(id); return filmService.deleteFilm(id);
} }
} }

View File

@ -1,15 +1,18 @@
package ru.ip.labs.labs.films.controller; package ru.ip.labs.labs.films.controller;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ip.labs.labs.films.dto.FilmDTO;
import ru.ip.labs.labs.films.dto.GenreDTO;
import ru.ip.labs.labs.films.models.Film; import ru.ip.labs.labs.films.models.Film;
import ru.ip.labs.labs.films.models.Genre; import ru.ip.labs.labs.films.models.Genre;
import ru.ip.labs.labs.films.service.FilmsService; import ru.ip.labs.labs.films.service.FilmsService;
import ru.ip.labs.labs.films.service.GenreService; import ru.ip.labs.labs.films.service.GenreService;
import javax.validation.Valid;
import java.util.List; import java.util.List;
@RestController @RestController
@RequestMapping("/genre") @RequestMapping("/genres")
public class GenreController { public class GenreController {
private final GenreService genreService; private final GenreService genreService;
@ -19,28 +22,28 @@ public class GenreController {
} }
@GetMapping("/{id}") @GetMapping("/{id}")
public Genre getGenre(@PathVariable Long id) { public GenreDTO getGenre(@PathVariable Long id) {
return genreService.findGenre(id); return genreService.findGenre(id);
} }
@GetMapping("/") @GetMapping("")
public List<Genre> getGenres() { public List<GenreDTO> getGenres() {
return genreService.findAllGenres(); return genreService.findAllGenres();
} }
@PostMapping("/") @PostMapping("")
public Genre createGenre(@RequestParam("name") String name) { public GenreDTO createGenre(@RequestBody @Valid GenreDTO genre) {
return genreService.addGenre(name); return genreService.addGenre(genre.getName());
} }
@PatchMapping("/{id}") @PatchMapping("/{id}")
public Genre updateGenre(@PathVariable Long id, public GenreDTO updateGenre(@PathVariable Long id,
@RequestParam("name") String name) { @RequestBody @Valid GenreDTO genre) {
return genreService.updateGenre(id, name); return genreService.updateGenre(id, genre.getName());
} }
@DeleteMapping("/{id}") @DeleteMapping("/{id}")
public Genre deleteGenre(@PathVariable Long id) { public GenreDTO deleteGenre(@PathVariable Long id) {
return genreService.deleteGenre(id); return genreService.deleteGenre(id);
} }
} }

View File

@ -0,0 +1,83 @@
package ru.ip.labs.labs.films.dto;
import ru.ip.labs.labs.films.models.Actor;
import ru.ip.labs.labs.films.models.Film;
import javax.persistence.FetchType;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.List;
public class ActorDTO {
private Long id;
private String name;
private String surname;
private String fullName;
private byte[] photo;
private List<Film> films;
public ActorDTO() {}
public ActorDTO(Actor actor) {
this.id = actor.getId();
this.name = actor.getName();
this.surname = actor.getSurname();
this.photo = actor.getPhoto();
this.fullName = this.name + this.surname;
}
public ActorDTO(Long id, String name, String surname, byte[] photo) {
this.id = id;
this.name = name;
this.surname = surname;
this.fullName = this.name + this.surname;
this.photo = photo;
}
public byte[] getPhoto() {
return photo;
}
public void setPhoto(String path) throws IOException {
File f = new File(path);
photo = Files.readAllBytes(f.toPath());
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public void setName(String name) {
this.name = name;
}
public List<Film> getFilms() {
return films;
}
@Override
public String toString() {
String res = "\nFilm{" +
"id: " + id + "," +
"name: " + name + "," +
"surname: " + name + "," +
"films:" + (films == null ? "[]" : films.toString()) + "}"
;
return res;
}
}

View File

@ -0,0 +1,74 @@
package ru.ip.labs.labs.films.dto;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import ru.ip.labs.labs.films.models.Actor;
import ru.ip.labs.labs.films.models.Film;
import ru.ip.labs.labs.films.models.Genre;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import java.util.List;
public class FilmDTO {
private Long id;
private String name;
private List<String> genre;
private List<Actor> actors;
public FilmDTO() {}
public FilmDTO(Film film) {
this.id = film.getId();
this.name = film.getName();
if(film.getGenres() == null) return;
this.genre = film.getGenres().stream().map(g -> {
return g.getName();
}).toList();
}
public FilmDTO(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void addGenre(String g) {
genre.add(g);
}
public void addActor(Actor actor) {
actors.add(actor);
}
public List<Actor> getActors() {
return actors;
}
public List<String> getGenre() {
return genre;
}
@Override
public String toString() {
String res = "\nFilm{" +
"id: " + id + "," +
"name: " + name + "," +
"genres:" + (genre == null ? "[]" : genre.toString()) + "}";
return res;
}
}

View File

@ -0,0 +1,39 @@
package ru.ip.labs.labs.films.dto;
import ru.ip.labs.labs.films.models.Genre;
public class GenreDTO {
private Long id;
private String name;
public GenreDTO() {}
public GenreDTO(Genre genre) {
this.id = genre.getId();
this.name = genre.getName();
}
public GenreDTO(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Genre{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

View File

@ -3,6 +3,7 @@ import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption; import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.*; import javax.persistence.*;
import java.util.ArrayList;
import java.util.Iterator; import java.util.Iterator;
import java.util.List; import java.util.List;
@ -47,10 +48,20 @@ public class Film {
} }
public void addGenre(Genre g) { public void addGenre(Genre g) {
if(genres == null) genres = new ArrayList<>();
genres.add(g); genres.add(g);
} }
public void deleteGenres() {
genres = null;
}
public void deleteActors() {
actors = null;
}
public void addActor(Actor actor) { public void addActor(Actor actor) {
if(actors == null) actors = new ArrayList<>();
actors.add(actor); actors.add(actor);
} }

View File

@ -0,0 +1,8 @@
package ru.ip.labs.labs.films.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ip.labs.labs.films.models.Actor;
public interface ActorRepository extends JpaRepository<Actor, Long> {
Actor findActorByNameAndSurname(String name, String surname);
}

View File

@ -0,0 +1,7 @@
package ru.ip.labs.labs.films.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ip.labs.labs.films.models.Film;
public interface FilmRepository extends JpaRepository<Film, Long> {
}

View File

@ -0,0 +1,8 @@
package ru.ip.labs.labs.films.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ip.labs.labs.films.models.Genre;
public interface GenreRepository extends JpaRepository<Genre, Long> {
Genre findByName(String name);
}

View File

@ -3,34 +3,39 @@ package ru.ip.labs.labs.films.service;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import ru.ip.labs.labs.films.dto.ActorDTO;
import ru.ip.labs.labs.films.models.Actor; import ru.ip.labs.labs.films.models.Actor;
import ru.ip.labs.labs.films.models.Film; import ru.ip.labs.labs.films.models.Film;
import ru.ip.labs.labs.films.repository.ActorRepository;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException; import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContext;
import java.io.IOException; import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Optional;
@Service @Service
public class ActorService { public class ActorService {
@PersistenceContext private ActorRepository repo;
private EntityManager em;
public ActorService(ActorRepository repo) {
this.repo = repo;
}
@Transactional @Transactional
public Actor addActor(String name, String surname) { public ActorDTO addActor(String name, String surname) {
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Student name is null or empty"); throw new IllegalArgumentException("Student name is null or empty");
} }
Actor actor = new Actor(name, surname); Actor actor = new Actor(name, surname);
em.persist(actor); return new ActorDTO(repo.save(actor));
return em.find(Actor.class, actor.getId());
} }
@Transactional @Transactional
public Actor addActor(String name, String surname, String path) { public ActorDTO addActor(String name, String surname, String path) {
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Student name is null or empty"); throw new IllegalArgumentException("Student name is null or empty");
} }
@ -39,47 +44,58 @@ public class ActorService {
try { try {
actor.setPhoto(path); actor.setPhoto(path);
} catch(IOException err) { } catch(IOException err) {
System.out.println(err.getMessage()); // System.out.println(err.getMessage());
throw new RuntimeException(err);
} }
em.persist(actor); return new ActorDTO(repo.save(actor));
return em.find(Actor.class, actor.getId());
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Actor findActor(Long id) { public ActorDTO findActor(Long id) {
final Actor actor = em.find(Actor.class, id); final Optional<Actor> actor = repo.findById(id);
if (actor == null) { if (actor.isEmpty()) {
throw new EntityNotFoundException(String.format("Actor with id [%s] is not found", id)); throw new EntityNotFoundException(String.format("Actor with id [%s] is not found", id));
} }
return actor; return new ActorDTO(actor.get());
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<Actor> findAllActors() { public List<ActorDTO> findAllActors() {
return em.createQuery("select f from Actor f", Actor.class) return repo.findAll().stream().map(x -> new ActorDTO(x)).toList();
.getResultList();
} }
@Transactional @Transactional
public Actor updateActor(Long id, String name, String surname) { public ActorDTO updateActor(Long id, String name, String surname) {
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Actor name is null or empty"); throw new IllegalArgumentException("Actor name is null or empty");
} }
final Actor currentActor = findActor(id); final Optional<Actor> currentActorOpt = repo.findById(id);
if(currentActorOpt.isEmpty()) {
return null;
}
final Actor currentActor = currentActorOpt.get();
if(name != null) currentActor.setName(name); if(name != null) currentActor.setName(name);
if(surname != null) currentActor.setSurname(surname); if(surname != null) currentActor.setSurname(surname);
return em.merge(currentActor);
return new ActorDTO(repo.save(currentActor));
} }
@Transactional @Transactional
public Actor deleteActor(Long id) { public ActorDTO deleteActor(Long id) {
final Actor currentActor = findActor(id); final Optional<Actor> currentActor = repo.findById(id);
em.remove(currentActor); if(currentActor.isEmpty()) {
return currentActor; return null;
}
repo.deleteById(id);
return new ActorDTO(currentActor.get());
} }
@Transactional @Transactional
public void deleteAllActors() { public void deleteAllActors() {
em.createQuery("delete from Actor").executeUpdate(); repo.deleteAll();
} }
} }

View File

@ -3,9 +3,13 @@ package ru.ip.labs.labs.films.service;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import ru.ip.labs.labs.films.dto.FilmDTO;
import ru.ip.labs.labs.films.models.Actor; import ru.ip.labs.labs.films.models.Actor;
import ru.ip.labs.labs.films.models.Film; import ru.ip.labs.labs.films.models.Film;
import ru.ip.labs.labs.films.models.Genre; import ru.ip.labs.labs.films.models.Genre;
import ru.ip.labs.labs.films.repository.ActorRepository;
import ru.ip.labs.labs.films.repository.FilmRepository;
import ru.ip.labs.labs.films.repository.GenreRepository;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException; import javax.persistence.EntityNotFoundException;
@ -13,6 +17,7 @@ import javax.persistence.PersistenceContext;
import javax.persistence.Query; import javax.persistence.Query;
import java.time.LocalDate; import java.time.LocalDate;
import java.util.List; import java.util.List;
import java.util.Optional;
@Service @Service
public class FilmsService { public class FilmsService {
@ -20,111 +25,166 @@ public class FilmsService {
@PersistenceContext @PersistenceContext
private EntityManager em; private EntityManager em;
private FilmRepository repo;
private GenreRepository repoGenre;
private ActorRepository repoActor;
public FilmsService(FilmRepository repo, GenreRepository repoGenre, ActorRepository repoActor) {
this.repo = repo;
this.repoGenre = repoGenre;
this.repoActor = repoActor;
}
@Transactional @Transactional
public Film addFilm(String name) { public FilmDTO addFilm(String name) {
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Student name is null or empty"); throw new IllegalArgumentException("Student name is null or empty");
} }
Film film = new Film(name); Film film = new Film(name);
return new FilmDTO(repo.save(film));
em.persist(film);
return em.find(Film.class, film.getId());
} }
// фильмы по жанру // фильмы по жанру
// фильмы по актеру // фильмы по актеру
@Transactional @Transactional
public Film addGenre(Long filmId, Long genreId) { public FilmDTO addGenre(Long filmId, Long genreId) {
final Film film = em.find(Film.class, filmId); final Film film = em.find(Film.class, filmId);
if (film == null) { if (film == null) {
throw new EntityNotFoundException(String.format("Film with id [%s] is not found", filmId)); throw new EntityNotFoundException(String.format("Film with id [%s] is not found", filmId));
} }
final Genre genre = em.find(Genre.class, genreId); final Optional<Genre> genre = repoGenre.findById(genreId);
if (genre == null) { if (genre.isEmpty()) {
throw new EntityNotFoundException(String.format("Genre with id [%s] is not found", genreId)); throw new EntityNotFoundException(String.format("Genre with id [%s] is not found", genreId));
} }
film.addGenre(genre); film.addGenre(genre.get());
return em.merge(film); return new FilmDTO(repo.save(film));
} }
@Transactional @Transactional
public Film addActor(Long filmId, Long actorId) { public FilmDTO updateGenres(Long filmId, List<String> genres) {
final Film film = em.find(Film.class, filmId);
if (film == null) {
throw new EntityNotFoundException(String.format("Film with id [%s] is not found", filmId));
}
film.deleteGenres();
for(String g : genres) {
Genre genre = repoGenre.findByName(g);
film.addGenre(genre);
}
return new FilmDTO(repo.save(film));
}
@Transactional
public FilmDTO updateActors(Long filmId, List<String> fullNames) {
final Film film = em.find(Film.class, filmId);
if (film == null) {
throw new EntityNotFoundException(String.format("Film with id [%s] is not found", filmId));
}
film.deleteActors();
for(String fn : fullNames) {
String arr[] = fn.split(" ");
Actor actor = repoActor.findActorByNameAndSurname(arr[0], arr[1]);
film.addActor(actor);
}
return new FilmDTO(repo.save(film));
}
@Transactional
public FilmDTO addActor(Long filmId, Long actorId) {
final Film film = em.find(Film.class, filmId); final Film film = em.find(Film.class, filmId);
if (film == null) { if (film == null) {
throw new EntityNotFoundException(String.format("Film with id [%s] is not found", filmId)); throw new EntityNotFoundException(String.format("Film with id [%s] is not found", filmId));
} }
final Actor actor = em.find(Actor.class, actorId); final Optional<Actor> actor = repoActor.findById(actorId);
if (actor == null) { if (actor == null) {
throw new EntityNotFoundException(String.format("Genre with id [%s] is not found", actorId)); throw new EntityNotFoundException(String.format("Genre with id [%s] is not found", actorId));
} }
film.addActor(actor); film.addActor(actor.get());
return em.merge(film); return new FilmDTO(repo.save(film));
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Film findFilm(Long id) { public FilmDTO findFilm(Long id) {
final Film film = em.find(Film.class, id); final Optional<Film> film = repo.findById(id);
if (film == null) { if (film.isEmpty()) {
throw new EntityNotFoundException(String.format("Film with id [%s] is not found", id)); throw new EntityNotFoundException(String.format("Film with id [%s] is not found", id));
} }
return film; return new FilmDTO(film.get());
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<Film> findFilmByGenre(Long id, Long genreId) { public List<FilmDTO> findFilmByGenre(Long id, Long genreId) {
Query query = em.createQuery("select f from Film f " + Query query = em.createQuery("select f from Film f " +
"join f.genres g " + "join f.genres g " +
"where g.id = :genreId", Film.class) "where g.id = :genreId", Film.class)
.setParameter("genreId", genreId); .setParameter("genreId", genreId);
List<Film> result = query.getResultList(); List<Film> result = query.getResultList();
return result; return result.stream().map(x -> new FilmDTO(x)).toList();
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<Film> findFilmByActor(Long id, String name) { public List<FilmDTO> findFilmByActor(Long id, String name) {
Query query = em.createQuery("select f from Film f " + Query query = em.createQuery("select f from Film f " +
"join f.actors a " + "join f.actors a " +
"where a.name like :actorName", Film.class) "where a.name like :actorName", Film.class)
.setParameter("actorName", '%' + name + '%'); .setParameter("actorName", '%' + name + '%');
List<Film> result = query.getResultList(); List<Film> result = query.getResultList();
return result; return result.stream().map(x -> new FilmDTO(x)).toList();
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<Film> findAllFilms() { public List<FilmDTO> findAllFilms() {
return em.createQuery("select f from Film f", Film.class) return repo.findAll().stream().map(x -> new FilmDTO(x)).toList();
.getResultList();
} }
@Transactional @Transactional
public Film updateFilm(Long id, String name) { public FilmDTO updateFilm(Long id, String name) {
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Film name is null or empty"); throw new IllegalArgumentException("Film name is null or empty");
} }
final Film currentFilm = findFilm(id); final Optional<Film> currentFilmOpt = repo.findById(id);
if(currentFilmOpt.isEmpty()) {
return null;
}
final Film currentFilm = currentFilmOpt.get();
currentFilm.setName(name); currentFilm.setName(name);
return em.merge(currentFilm); return new FilmDTO(repo.save(currentFilm));
} }
@Transactional @Transactional
public Film deleteFilm(Long id) { public FilmDTO deleteFilm(Long id) {
final Film currentFilm = findFilm(id); final Optional<Film> currentFilm = repo.findById(id);
em.remove(currentFilm); if(currentFilm.isEmpty()) {
return currentFilm; return null;
}
repo.deleteById(id);
return new FilmDTO(currentFilm.get());
} }
@Transactional @Transactional
public void deleteAllFilms() { public void deleteAllFilms() {
em.createQuery("delete from Film").executeUpdate(); repo.deleteAll();
} }
} }

View File

@ -3,66 +3,80 @@ package ru.ip.labs.labs.films.service;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import ru.ip.labs.labs.films.dto.GenreDTO;
import ru.ip.labs.labs.films.models.Film; import ru.ip.labs.labs.films.models.Film;
import ru.ip.labs.labs.films.models.Genre; import ru.ip.labs.labs.films.models.Genre;
import ru.ip.labs.labs.films.repository.ActorRepository;
import ru.ip.labs.labs.films.repository.GenreRepository;
import javax.persistence.EntityManager; import javax.persistence.EntityManager;
import javax.persistence.EntityNotFoundException; import javax.persistence.EntityNotFoundException;
import javax.persistence.PersistenceContext; import javax.persistence.PersistenceContext;
import java.util.List; import java.util.List;
import java.util.Optional;
@Service @Service
public class GenreService { public class GenreService {
@PersistenceContext private GenreRepository repo;
private EntityManager em;
public GenreService(GenreRepository repo) {
this.repo = repo;
}
@Transactional @Transactional
public Genre addGenre(String name) { public GenreDTO addGenre(String name) {
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Genre name is null or empty"); throw new IllegalArgumentException("Genre name is null or empty");
} }
Genre genre = new Genre(name); Genre genre = new Genre(name);
return new GenreDTO(repo.save(genre));
em.persist(genre);
return em.find(Genre.class, genre.getId());
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Genre findGenre(Long id) { public GenreDTO findGenre(Long id) {
final Genre genre = em.find(Genre.class, id); final Optional<Genre> genre = repo.findById(id);
if (genre == null) { if (genre.isEmpty()) {
throw new EntityNotFoundException(String.format("Genre with id [%s] is not found", id)); throw new EntityNotFoundException(String.format("Genre with id [%s] is not found", id));
} }
return genre; return new GenreDTO(genre.get());
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<Genre> findAllGenres() { public List<GenreDTO> findAllGenres() {
return em.createQuery("select g from Genre g", Genre.class) return repo.findAll().stream().map(x -> new GenreDTO(x)).toList();
.getResultList();
} }
@Transactional @Transactional
public Genre updateGenre(Long id, String name) { public GenreDTO updateGenre(Long id, String name) {
if (!StringUtils.hasText(name)) { if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Film name is null or empty"); throw new IllegalArgumentException("Film name is null or empty");
} }
final Genre currentGenre = findGenre(id); final Optional<Genre> currentGenreOpt = repo.findById(id);
if(currentGenreOpt.isEmpty()) {
return null;
}
final Genre currentGenre = currentGenreOpt.get();
currentGenre.setName(name); currentGenre.setName(name);
return em.merge(currentGenre); return new GenreDTO(repo.save(currentGenre));
} }
@Transactional @Transactional
public Genre deleteGenre(Long id) { public GenreDTO deleteGenre(Long id) {
final Genre currentGenre = findGenre(id); Optional<Genre> genre = repo.findById(id);
em.remove(currentGenre); if(genre.isEmpty()) {
return currentGenre; return null;
}
repo.deleteById(id);
return new GenreDTO(genre.get());
} }
@Transactional @Transactional
public void deleteAllGenres() { public void deleteAllGenres() {
em.createQuery("delete from Genre").executeUpdate(); repo.deleteAll();
} }
} }

View File

@ -6,6 +6,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import ru.ip.labs.labs.films.dto.ActorDTO;
import ru.ip.labs.labs.films.dto.FilmDTO;
import ru.ip.labs.labs.films.models.Actor; import ru.ip.labs.labs.films.models.Actor;
import ru.ip.labs.labs.films.models.Film; import ru.ip.labs.labs.films.models.Film;
import ru.ip.labs.labs.films.models.Genre; import ru.ip.labs.labs.films.models.Genre;
@ -26,52 +28,57 @@ public class JpaActorsTest {
ActorService actorService; ActorService actorService;
@Test @Test
void testFilmCreate() { void testActorCreate() {
filmService.deleteAllFilms();
actorService.deleteAllActors(); actorService.deleteAllActors();
final Actor actor = actorService.addActor("Victor", "Ivanov"); final ActorDTO actor = actorService.addActor("Victor", "Ivanov");
log.info(actor.toString()); log.info(actor.toString());
Assertions.assertNotNull(actor.getId()); Assertions.assertNotNull(actor.getId());
} }
@Test @Test
void testFilmReadNotFound() { void testActorReadNotFound() {
actorService.deleteAllActors(); actorService.deleteAllActors();
Assertions.assertThrows(EntityNotFoundException.class, () -> actorService.findActor(-1L)); Assertions.assertThrows(EntityNotFoundException.class, () -> actorService.findActor(-1L));
} }
@Test @Test
void findFilm() { void findActor() {
filmService.deleteAllFilms();
actorService.deleteAllActors(); actorService.deleteAllActors();
final Actor actor = actorService.addActor("Victor", "Ivanov"); final ActorDTO actor = actorService.addActor("Victor", "Ivanov");
log.info(actor.toString()); log.info(actor.toString());
final Actor findActor = actorService.findActor(actor.getId()); final ActorDTO findActor = actorService.findActor(actor.getId());
log.info(findActor.toString()); log.info(findActor.toString());
Assertions.assertEquals(actor.toString(), findActor.toString()); Assertions.assertEquals(actor.toString(), findActor.toString());
} }
@Test @Test
void testReadAll() { void testReadAll() {
filmService.deleteAllFilms();
actorService.deleteAllActors(); actorService.deleteAllActors();
final Actor actor = actorService.addActor("Victor", "Ivanov"); final ActorDTO actor = actorService.addActor("Victor", "Ivanov");
log.info(actor.toString()); log.info(actor.toString());
final List<Actor> actors = actorService.findAllActors(); final List<ActorDTO> actors = actorService.findAllActors();
Assertions.assertEquals(actors.size(), 1); Assertions.assertEquals(actors.size(), 1);
} }
@Test @Test
void updateActor() { void updateActor() {
filmService.deleteAllFilms();
actorService.deleteAllActors(); actorService.deleteAllActors();
final Actor actor = actorService.addActor("Victor", "Ivanov"); final ActorDTO actor = actorService.addActor("Victor", "Ivanov");
actorService.updateActor(actor.getId(), "Terminator", null); actorService.updateActor(actor.getId(), "Terminator", null);
final Actor findActor = actorService.findActor(actor.getId()); final ActorDTO findActor = actorService.findActor(actor.getId());
log.info(findActor.toString()); log.info(findActor.toString());
Assertions.assertEquals(findActor.getName() + " " + findActor.getSurname(), "Terminator Ivanov"); Assertions.assertEquals(findActor.getName() + " " + findActor.getSurname(), "Terminator Ivanov");
} }
@Test @Test
void deleteActor() { void deleteActor() {
filmService.deleteAllFilms();
actorService.deleteAllActors(); actorService.deleteAllActors();
final Actor actor = actorService.addActor("Victor", "Ivanov"); final ActorDTO actor = actorService.addActor("Victor", "Ivanov");
log.info(actor.toString()); log.info(actor.toString());
actorService.deleteActor(actor.getId()); actorService.deleteActor(actor.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> actorService.findActor(actor.getId())); Assertions.assertThrows(EntityNotFoundException.class, () -> actorService.findActor(actor.getId()));
@ -79,22 +86,23 @@ public class JpaActorsTest {
@Test @Test
void addPhoto() { void addPhoto() {
filmService.deleteAllFilms();
actorService.deleteAllActors(); actorService.deleteAllActors();
final Actor actor = actorService.addActor("Victor", "Ivanov", "C:\\Users\\админ\\Pictures\\Screenshots\\Снимок экрана (2).png"); final ActorDTO actor = actorService.addActor("Victor", "Ivanov", "C:\\Users\\parap\\OneDrive\\Рабочий стол\\work\\ferrari.jpg");
Actor findActor = actorService.findActor(actor.getId()); ActorDTO findActor = actorService.findActor(actor.getId());
Assertions.assertNotEquals(findActor.getPhoto().length, 0); Assertions.assertNotEquals(findActor.getPhoto().length, 0);
} }
@Test @Test
void addFilm() { void addFilm() {
actorService.deleteAllActors();
filmService.findAllFilms(); filmService.findAllFilms();
final Actor actor = actorService.addActor("Victor", "Ivanov"); actorService.deleteAllActors();
final Film film = filmService.addFilm("Terminator 2"); final ActorDTO actor = actorService.addActor("Victor", "Ivanov");
final FilmDTO film = filmService.addFilm("Terminator 2");
filmService.addActor(film.getId(), actor.getId()); filmService.addActor(film.getId(), actor.getId());
final Actor findActor = actorService.findActor(actor.getId()); final ActorDTO findActor = actorService.findActor(actor.getId());
Assertions.assertEquals(findActor.getFilms().get(0).getId(), film.getId()); Assertions.assertEquals(findActor.getFilms().get(0).getId(), film.getId());
} }
} }

View File

@ -5,6 +5,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import ru.ip.labs.labs.films.dto.ActorDTO;
import ru.ip.labs.labs.films.dto.FilmDTO;
import ru.ip.labs.labs.films.models.Actor; import ru.ip.labs.labs.films.models.Actor;
import ru.ip.labs.labs.films.models.Film; import ru.ip.labs.labs.films.models.Film;
import ru.ip.labs.labs.films.models.Genre; import ru.ip.labs.labs.films.models.Genre;
@ -30,7 +32,7 @@ public class JpaFilmsTest {
@Test @Test
void testFilmCreate() { void testFilmCreate() {
filmService.deleteAllFilms(); filmService.deleteAllFilms();
final Film film = filmService.addFilm("Terminator 2"); final FilmDTO film = filmService.addFilm("Terminator 2");
log.info(film.toString()); log.info(film.toString());
Assertions.assertNotNull(film.getId()); Assertions.assertNotNull(film.getId());
} }
@ -44,9 +46,9 @@ public class JpaFilmsTest {
@Test @Test
void findFilm() { void findFilm() {
filmService.deleteAllFilms(); filmService.deleteAllFilms();
final Film film = filmService.addFilm("Terminator 2"); final FilmDTO film = filmService.addFilm("Terminator 2");
log.info(film.toString()); log.info(film.toString());
final Film findFilm = filmService.findFilm(film.getId()); final FilmDTO findFilm = filmService.findFilm(film.getId());
log.info(findFilm.toString()); log.info(findFilm.toString());
Assertions.assertEquals(film.toString(), findFilm.toString()); Assertions.assertEquals(film.toString(), findFilm.toString());
} }
@ -54,9 +56,9 @@ public class JpaFilmsTest {
@Test @Test
void updateFilm() { void updateFilm() {
filmService.deleteAllFilms(); filmService.deleteAllFilms();
final Film film = filmService.addFilm("Terminator 2"); final FilmDTO film = filmService.addFilm("Terminator 2");
filmService.updateFilm(film.getId(), "Terminator 3"); filmService.updateFilm(film.getId(), "Terminator 3");
final Film findFilm = filmService.findFilm(film.getId()); final FilmDTO findFilm = filmService.findFilm(film.getId());
log.info(findFilm.toString()); log.info(findFilm.toString());
Assertions.assertEquals(findFilm.getName(), "Terminator 3"); Assertions.assertEquals(findFilm.getName(), "Terminator 3");
} }
@ -64,16 +66,16 @@ public class JpaFilmsTest {
@Test @Test
void testReadAll() { void testReadAll() {
filmService.deleteAllFilms(); filmService.deleteAllFilms();
final Film film = filmService.addFilm("Terminator 2"); final FilmDTO film = filmService.addFilm("Terminator 2");
log.info(film.toString()); log.info(film.toString());
final List<Film> films = filmService.findAllFilms(); final List<FilmDTO> films = filmService.findAllFilms();
Assertions.assertEquals(films.size(), 1); Assertions.assertEquals(films.size(), 1);
} }
@Test @Test
void deleteFilm() { void deleteFilm() {
filmService.deleteAllFilms(); filmService.deleteAllFilms();
final Film film = filmService.addFilm("Terminator 2"); final FilmDTO film = filmService.addFilm("Terminator 2");
log.info(film.toString()); log.info(film.toString());
filmService.deleteFilm(film.getId()); filmService.deleteFilm(film.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> filmService.findFilm(film.getId())); Assertions.assertThrows(EntityNotFoundException.class, () -> filmService.findFilm(film.getId()));
@ -83,30 +85,30 @@ public class JpaFilmsTest {
void findFilmsByGenres() { void findFilmsByGenres() {
filmService.deleteAllFilms(); filmService.deleteAllFilms();
genreService.deleteAllGenres(); genreService.deleteAllGenres();
final Film film = filmService.addFilm("Terminator 2"); // final FilmDTO film = filmService.addFilm("Terminator 2");
filmService.addFilm("Terminator 3"); // filmService.addFilm("Terminator 3");
final Genre genre = genreService.addGenre("Comedy"); // final Genre genre = genreService.addGenre("Comedy");
//
filmService.addGenre(film.getId(), genre.getId()); // filmService.addGenre(film.getId(), genre.getId());
//
final List<Film> films = filmService.findFilmByGenre(film.getId(), genre.getId()); // final List<FilmDTO> films = filmService.findFilmByGenre(film.getId(), genre.getId());
Assertions.assertEquals(films.size(), 1); // Assertions.assertEquals(films.size(), 1);
} }
@Test @Test
void findFilmsByActor() { void findFilmsByActor() {
filmService.deleteAllFilms(); filmService.deleteAllFilms();
genreService.deleteAllGenres(); genreService.deleteAllGenres();
final Film film = filmService.addFilm("Terminator 2"); final FilmDTO film = filmService.addFilm("Terminator 2");
final Film film2 = filmService.addFilm("Terminator 3"); final FilmDTO film2 = filmService.addFilm("Terminator 3");
filmService.addFilm("Terminator 4"); filmService.addFilm("Terminator 4");
final Actor actor = actorService.addActor("Victor", "Ivanov"); final ActorDTO actor = actorService.addActor("Victor", "Ivanov");
final Actor actor2 = actorService.addActor("Victoria", "Ivanov"); final ActorDTO actor2 = actorService.addActor("Victoria", "Ivanov");
filmService.addActor(film.getId(), actor.getId()); filmService.addActor(film.getId(), actor.getId());
filmService.addActor(film2.getId(), actor2.getId()); filmService.addActor(film2.getId(), actor2.getId());
final List<Film> films = filmService.findFilmByActor(film.getId(), "Victor"); final List<FilmDTO> films = filmService.findFilmByActor(film.getId(), "Victor");
Assertions.assertEquals(films.size(), 2); Assertions.assertEquals(films.size(), 2);
} }
@ -114,25 +116,25 @@ public class JpaFilmsTest {
void addGenre() { void addGenre() {
filmService.deleteAllFilms(); filmService.deleteAllFilms();
genreService.deleteAllGenres(); genreService.deleteAllGenres();
final Film film = filmService.addFilm("Terminator 2"); final FilmDTO film = filmService.addFilm("Terminator 2");
final Genre genre = genreService.addGenre("Comedy"); // final Genre genre = genreService.addGenre("Comedy");
//
filmService.addGenre(film.getId(), genre.getId()); // filmService.addGenre(film.getId(), genre.getId());
//
final Film findFilm = filmService.findFilm(film.getId()); // final FilmDTO findFilm = filmService.findFilm(film.getId());
Assertions.assertEquals(findFilm.getGenres().get(0).toString(), genre.toString()); // Assertions.assertEquals(findFilm.getGenre().get(0).toString(), genre.toString());
} }
@Test @Test
void addActor() { void addActor() {
filmService.deleteAllFilms(); filmService.deleteAllFilms();
genreService.deleteAllGenres(); genreService.deleteAllGenres();
final Film film = filmService.addFilm("Terminator 2"); final FilmDTO film = filmService.addFilm("Terminator 2");
final Actor actor = actorService.addActor("Victor", "Ivanov"); final ActorDTO actor = actorService.addActor("Victor", "Ivanov");
filmService.addActor(film.getId(), actor.getId()); filmService.addActor(film.getId(), actor.getId());
final Film findFilm = filmService.findFilm(film.getId()); final FilmDTO findFilm = filmService.findFilm(film.getId());
Assertions.assertEquals(findFilm.getActors().get(0).getId(), actor.getId()); Assertions.assertEquals(findFilm.getActors().get(0).getId(), actor.getId());
} }
} }

View File

@ -6,6 +6,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import ru.ip.labs.labs.films.dto.GenreDTO;
import ru.ip.labs.labs.films.models.Film; import ru.ip.labs.labs.films.models.Film;
import ru.ip.labs.labs.films.models.Genre; import ru.ip.labs.labs.films.models.Genre;
import ru.ip.labs.labs.films.service.FilmsService; import ru.ip.labs.labs.films.service.FilmsService;
@ -26,7 +27,7 @@ public class JpaGenresTest {
@Test @Test
void testGenreCreate() { void testGenreCreate() {
genreService.deleteAllGenres(); genreService.deleteAllGenres();
final Genre genre = genreService.addGenre("Comedy"); final GenreDTO genre = genreService.addGenre("Comedy");
log.info(genre.toString()); log.info(genre.toString());
Assertions.assertNotNull(genre.getId()); Assertions.assertNotNull(genre.getId());
} }
@ -40,9 +41,9 @@ public class JpaGenresTest {
@Test @Test
void findGenre() { void findGenre() {
genreService.deleteAllGenres(); genreService.deleteAllGenres();
final Genre genre = genreService.addGenre("Comedy"); final GenreDTO genre = genreService.addGenre("Comedy");
log.info(genre.toString()); log.info(genre.toString());
final Genre findGenre = genreService.findGenre(genre.getId()); final GenreDTO findGenre = genreService.findGenre(genre.getId());
log.info(findGenre.toString()); log.info(findGenre.toString());
Assertions.assertEquals(genre.toString(), findGenre.toString()); Assertions.assertEquals(genre.toString(), findGenre.toString());
} }
@ -50,18 +51,18 @@ public class JpaGenresTest {
@Test @Test
void testReadAll() { void testReadAll() {
genreService.deleteAllGenres(); genreService.deleteAllGenres();
final Genre genre = genreService.addGenre("Comedy"); final GenreDTO genre = genreService.addGenre("Comedy");
log.info(genre.toString()); log.info(genre.toString());
final List<Genre> genres = genreService.findAllGenres(); final List<GenreDTO> genres = genreService.findAllGenres();
Assertions.assertEquals(genres.size(), 1); Assertions.assertEquals(genres.size(), 1);
} }
@Test @Test
void updateGenre() { void updateGenre() {
genreService.deleteAllGenres(); genreService.deleteAllGenres();
final Genre genre = genreService.addGenre("Comedy"); final GenreDTO genre = genreService.addGenre("Comedy");
genreService.updateGenre(genre.getId(), "Drama"); genreService.updateGenre(genre.getId(), "Drama");
final Genre findGenre = genreService.findGenre(genre.getId()); final GenreDTO findGenre = genreService.findGenre(genre.getId());
log.info(findGenre.toString()); log.info(findGenre.toString());
Assertions.assertEquals(findGenre.getName(), "Drama"); Assertions.assertEquals(findGenre.getName(), "Drama");
} }
@ -69,7 +70,7 @@ public class JpaGenresTest {
@Test @Test
void deleteGenre() { void deleteGenre() {
genreService.deleteAllGenres(); genreService.deleteAllGenres();
final Genre genre = genreService.addGenre("Comedy"); final GenreDTO genre = genreService.addGenre("Comedy");
log.info(genre.toString()); log.info(genre.toString());
genreService.deleteGenre(genre.getId()); genreService.deleteGenre(genre.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> filmService.findFilm(genre.getId())); Assertions.assertThrows(EntityNotFoundException.class, () -> filmService.findFilm(genre.getId()));