4 lab without front

This commit is contained in:
Татьяна Артамонова 2023-05-11 02:47:12 +04:00
parent feefeadbd3
commit e9c6b563e4
22 changed files with 509 additions and 406 deletions

View File

@ -17,6 +17,8 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation 'com.h2database:h2:2.1.210'
implementation group: 'org.springdoc', name: 'springdoc-openapi-ui', version: '1.6.5'
implementation 'org.jetbrains:annotations:24.0.0'
implementation 'org.jetbrains:annotations:24.0.0'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

View File

@ -2,109 +2,67 @@
<html>
<head>
<meta charset="UTF-8">
<title>LabWork02</title>
<title>LabWork04</title>
<script src="/node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="/node_modules/bootstrap/dist/css/bootstrap.min.css">
</head>
<body class="bg-light">
<div class="container">
<div class="py-5 text-center"><h2>Лабораторная работа 2</h2></div>
<div class="row">
<div>
<form>
<div class="row">
<div class="col-md-6 mb-3">
<label for="input1">Значение 1 (string или double)</label>
<input class="form-control" id="input1" placeholder="Введите значение 1">
</div>
<div class="col-md-6 mb-3">
<label for="input1">Значение 2 (string или double)</label>
<input class="form-control" id="input2" placeholder="Введите значение 2">
</div>
</div>
<div class="row">
<div class="form-group">
<label for="operator">Выберите функцию</label>
<select class="form-control" id="operator">
<option value>Выбрать...</option>
<option value="Func1">(string, double)Сумма</option>
<option value="Func2">(double)Минимум, (string)Сумма в верхний регистр</option>
<option value="Func3">(double)Mаксимум, (string)Разделить</option>
<option value="Func4">(double)Число 1 в степени числа 2, (string)Сумма в нижний регистр</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="operator">Выберите тип данных</label>
<select class="form-control" id="Type">
<option value>Выбрать...</option>
<option value="str">String</option>
<option value="double">Double</option>
</select>
</div>
</div>
<div class="row">
<div class="form-group">
<label for="result">Результат</label>
<input type="text" class="form-control result" id="result" readonly>
<hr class="mb-4">
<button type="button" class="btn btn-primary btn-block" onclick="calculate()">Посчитать</button>
</div>
</div>
</form>
</div>
</div>
</div>
<!--<div class="container mt-4">-->
<!-- <div class="row justify-content-center">-->
<!-- <div class="col-lg-6">-->
<!-- <h3 class="text-center font-weight-light my-2">Лабораторная работа 2</h3>-->
<div id="like_button_container"></div>
<!-- <div class="container">-->
<!-- <div class="py-5 text-center"><h2>Лабораторная работа 2</h2></div>-->
<!-- <div class="row">-->
<!-- <div>-->
<!-- <form>-->
<!-- <div class="form-row">-->
<!-- <div class="col">-->
<!-- <div class="form-group">-->
<!-- <div class="row">-->
<!-- <div class="col-md-6 mb-3">-->
<!-- <label for="input1">Значение 1 (string или double)</label>-->
<!-- <input class="form-control" id="input1" placeholder="Введите значение 1">-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="col">-->
<!-- <div class="form-group">-->
<!-- <label for="input2">Значение 2 (string или double)</label>-->
<!-- <div class="col-md-6 mb-3">-->
<!-- <label for="input1">Значение 2 (string или double)</label>-->
<!-- <input class="form-control" id="input2" placeholder="Введите значение 2">-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="col">-->
<!-- <div class="row">-->
<!-- <div class="form-group">-->
<!-- <label for="operator">Выбрать функцию...</label>-->
<!-- <label for="operator">Выберите функцию</label>-->
<!-- <select class="form-control" id="operator">-->
<!-- <option value="Func1">Сумма</option>-->
<!-- <option value="Func2">Минимум, Сумма в верхний регистр</option>-->
<!-- <option value="Func3">Mаксимум, Разделить</option>-->
<!-- <option value="Func4">Число 1 в степени числа 2, Сумма в нижний регистр</option>-->
<!-- <option value>Выбрать...</option>-->
<!-- <option value="Func1">(string, double)Сумма</option>-->
<!-- <option value="Func2">(double)Минимум, (string)Сумма в верхний регистр</option>-->
<!-- <option value="Func3">(double)Mаксимум, (string)Разделить</option>-->
<!-- <option value="Func4">(double)Число 1 в степени числа 2, (string)Сумма в нижний регистр</option>-->
<!-- </select>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="col">-->
<!-- <div class="row">-->
<!-- <div class="form-group">-->
<!-- <label for="operator">Выбрать тип данных...</label>-->
<!-- <label for="operator">Выберите тип данных</label>-->
<!-- <select class="form-control" id="Type">-->
<!-- <option value>Выбрать...</option>-->
<!-- <option value="str">String</option>-->
<!-- <option value="double">Double</option>-->
<!-- </select>-->
<!-- </div>-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="row">-->
<!-- <div class="form-group">-->
<!-- <label for="result">Результат</label>-->
<!-- <input type="text" class="form-control result" id="result" readonly>-->
<!-- </div>-->
<!-- <hr class="mb-4">-->
<!-- <button type="button" class="btn btn-primary btn-block" onclick="calculate()">Посчитать</button>-->
<!-- </div>-->
<!-- </div>-->
<!-- </form>-->
<!-- </div>-->
<!-- </div>-->
<!--</div>-->
<script src = "script.js"></script>
<!-- </div>-->
<script src = "script.js"></script>
<!-- Загрузим React. -->
<script src="https://unpkg.com/react@18/umd/react.development.js" crossorigin></script>
<script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js" crossorigin></script>
<!-- Загрузим наш React-компонент. -->
<script src="react.js"></script>
</body>
</html>

25
front/react.js vendored Normal file
View File

@ -0,0 +1,25 @@
'use strict';
const e = React.createElement;
class LikeButton extends React.Component {
constructor(props) {
super(props);
this.state = { liked: false };
}
render() {
if (this.state.liked) {
return 'You liked this.';
}
return e(
'button',
{ onClick: () => this.setState({ liked: true }) },
'Like'
);
}
}
const domContainer = document.querySelector('#like_button_container');
const root = ReactDOM.createRoot(domContainer);
root.render(e(LikeButton));

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.database.model.Album;
public interface IAlbumRepository extends JpaRepository<Album, Long> {
}

View File

@ -0,0 +1,14 @@
package ru.ulstu.is.sbapp.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import java.util.List;
public interface IArtistRepository extends JpaRepository<Artist, Long> {
@Query("SELECT DISTINCT a.songs FROM Album a where :artist MEMBER OF a.artists")
List<Song> getSongs(@Param("artist") Artist artist);
}

View File

@ -0,0 +1,13 @@
package ru.ulstu.is.sbapp.Repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import ru.ulstu.is.sbapp.database.model.Song;
import java.util.List;
public interface ISongRepository extends JpaRepository<Song, Long> {
@Query("SELECT s.songs FROM Album s WHERE :song MEMBER OF s.songs")
List<Song> findSongsInAlbum(@Param("song") Song song);
}

View File

@ -0,0 +1,43 @@
package ru.ulstu.is.sbapp.controllers;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.database.service.AlbumService;
import java.util.List;
@RestController
@RequestMapping("/album")
public class AlbumController {
private final AlbumService albumService;
public AlbumController(AlbumService albumService){
this.albumService = albumService;
}
@PostMapping
public AlbumDTO addAlbum(@RequestBody @Validated AlbumDTO albumDTO){
return new AlbumDTO(albumService.addAlbum(albumDTO));
}
@PutMapping("/{id}")
public AlbumDTO updateAlbum(@PathVariable Long id, @RequestBody @Validated AlbumDTO albumDTO){
return new AlbumDTO(albumService.updateAlbum(id, albumDTO));
}
@DeleteMapping("/{id}")
public AlbumDTO removeAlbum(@PathVariable Long id){
return new AlbumDTO(albumService.deleteAlbum(id));
}
@DeleteMapping
public void removeAllAlbums(){
albumService.deleteAllAlbums();
}
@GetMapping("/{id}")
public AlbumDTO findAlbum(@PathVariable Long id){
return new AlbumDTO(albumService.findAlbum(id));
}
@GetMapping
public List<AlbumDTO> findAllAlbums(){
return albumService.findAllAlbums()
.stream()
.map(x -> new AlbumDTO(x))
.toList();
}
}

View File

@ -0,0 +1,38 @@
package ru.ulstu.is.sbapp.controllers;
import ru.ulstu.is.sbapp.database.model.Album;
import java.util.List;
public class AlbumDTO {
private long id;
private String albumName;
private List<SongDTO> songDTOList;
private List<ArtistDTO> artistDTOList;
public AlbumDTO(Album album){
this.id = album.getId();
this.albumName = album.getAlbumName();
this.artistDTOList = album.getArtists() == null ? null : album.getArtists()
.stream()
.filter(x -> x.getAlbum().contains(album))
.map(ArtistDTO::new)
.toList();
this.songDTOList = album.getSongs() == null ? null : album.getSongs()
.stream()
.map(SongDTO::new)
.toList();
}
public AlbumDTO(){}
public long getId() {
return id;
}
public String getAlbumName(){
return albumName;
}
public List<SongDTO> getSongDTOList(){
return songDTOList;
}
public List<ArtistDTO> getArtistDTOList(){
return artistDTOList;
}
}

View File

@ -0,0 +1,54 @@
package ru.ulstu.is.sbapp.controllers;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.database.service.ArtistService;
import java.util.List;
@RestController
@RequestMapping("/artist")
public class ArtistController {
private final ArtistService artistService;
public ArtistController(ArtistService artistService){
this.artistService = artistService;
}
@PostMapping
public ArtistDTO addArtist(@RequestBody @Validated ArtistDTO artistDTO) {
return new ArtistDTO(artistService.addArtist(artistDTO));
}
@PutMapping("/{id}")
public ArtistDTO updateArtist(@PathVariable Long id,@RequestBody @Validated ArtistDTO artistDTO) {
return new ArtistDTO(artistService.updateArtist(id, artistDTO));
}
@DeleteMapping("/{id}")
public ArtistDTO removeArtist(@PathVariable Long id) {
return new ArtistDTO(artistService.deleteArtist(id));
}
@DeleteMapping
public void removeAllArtists() {
artistService.deleteAllArtists();
}
@GetMapping("/{id}")
public ArtistDTO findArtist(@PathVariable Long id) {
return new ArtistDTO(artistService.findArtist(id));
}
@GetMapping("/worker/{id}")
public List<SongDTO> findSongsOnWorkplace(@PathVariable Long id){
return artistService.findAllSongsProducedArtist(id)
.stream()
.map(SongDTO::new)
.toList();
}
@GetMapping
public List<ArtistDTO> findAllArtist() {
return artistService.findAllArtists()
.stream()
.map(ArtistDTO::new)
.toList();
}
}

View File

@ -0,0 +1,38 @@
package ru.ulstu.is.sbapp.controllers;
import ru.ulstu.is.sbapp.database.model.Artist;
import java.util.List;
public class ArtistDTO {
private long id;
private String artistName;
private String genre;
private List<AlbumDTO> albumDTOList;
public ArtistDTO(Artist artist){
this.id = artist.getId();
this.artistName = artist.getArtistName();
this.genre = artist.getGenre();
this.albumDTOList = artist.getAlbum() == null ? null : artist.getAlbum()
.stream()
.filter(x -> x.getArtists().contains(artist.getId()))
.map(y -> new AlbumDTO(y))
.toList();
}
public ArtistDTO() {
}
public long getId() {
return id;
}
public String getArtistName() {
return artistName;
}
public String getGenre() {
return genre;
}
public List<AlbumDTO> getAlbumDTOList(){
return albumDTOList;
}
}

View File

@ -0,0 +1,53 @@
package ru.ulstu.is.sbapp.controllers;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.database.service.SongService;
import java.util.List;
@RestController
@RequestMapping("/song")
public class SongController {
private final SongService songService;
public SongController(SongService songService){
this.songService = songService;
}
@PostMapping
public SongDTO addSong(@RequestBody @Validated SongDTO songDTO) {
return new SongDTO(songService.addSong(songDTO));
}
@PutMapping("/{id}")
public SongDTO updateSong(@PathVariable Long id,@RequestBody @Validated SongDTO songDTO) {
return new SongDTO(songService.updateSong(id, songDTO));
}
@DeleteMapping("/{id}")
public SongDTO removeSong(@PathVariable Long id) {
return new SongDTO(songService.deleteSong(id));
}
@DeleteMapping
public void removeAllSongs() {
songService.deleteAllSongs();
}
@GetMapping("/{id}")
public SongDTO findSong(@PathVariable Long id) {
return new SongDTO(songService.findSong(id));
}
@GetMapping("/workplace/{id}")
public List<SongDTO> findSongsOnWorkplace(@PathVariable Long id){
return songService.findSongsInAlbum(id).stream()
.map(SongDTO::new)
.toList();
}
@GetMapping
public List<SongDTO> findAllSong() {
return songService.findAllSongs()
.stream()
.map(x-> new SongDTO(x))
.toList();
}
}

View File

@ -0,0 +1,25 @@
package ru.ulstu.is.sbapp.controllers;
import ru.ulstu.is.sbapp.database.model.Song;
public class SongDTO {
private Long id;
private String songName;
private Double Duration;
public SongDTO(Song song){
this.id = song.getId();
this.songName = song.getSongName();
this.Duration = song.getSongDuration();
}
public SongDTO(){
}
public Long getId() {
return id;
}
public String getSongName(){
return songName;
}
public Double getSongDuration(){
return Duration;
}
}

View File

@ -1,6 +1,8 @@
package ru.ulstu.is.sbapp.database.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@ -10,7 +12,8 @@ import java.util.Objects;
public class Album {
@Id
@GeneratedValue
private Long id;
private long id;
@NotNull(message = "Name can't be empty")
@Column(name = "name")
private String albumName;
@OneToMany(cascade = {CascadeType.MERGE})
@ -23,8 +26,10 @@ public class Album {
private List<Artist> artists;
public Album(){
}
public Album(String albumName){
public Album(String albumName, List<Artist> artists, List<Song> songs){
this.albumName = albumName;
this.artists = artists;
this.songs = songs;
}
public Long getId() {
return id;
@ -43,6 +48,9 @@ public class Album {
public void setArtists(List<Artist> artists) {
this.artists = artists;
}
public void setSongs(List<Song> songs) {
this.songs = songs;
}
public void update(Album album){
this.albumName = album.albumName;
this.artists = album.getArtists();
@ -68,13 +76,13 @@ public class Album {
}
if (!songs.contains(song)) {
this.songs.add(song);
song.setAlbum(this);
}
}
public void removeSong(Song song){
if (songs.contains(song))
if (songs.contains(song)) {
this.songs.remove(song);
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;

View File

@ -1,6 +1,8 @@
package ru.ulstu.is.sbapp.database.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@ -10,11 +12,13 @@ public class Artist {
@Id
@GeneratedValue
private Long id;
@Column(name = "name")
@NotNull(message = "Name can't be empty")
@Column(name = "artistName")
private String artistName;
@NotNull(message = "Genre can't be null or empty")
@Column(name = "genre")
private String genre;
@ManyToMany(mappedBy = "artists", cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
@ManyToMany(mappedBy = "artists",cascade = CascadeType.MERGE, fetch = FetchType.EAGER)
private List<Album> album;
public Artist() {
}

View File

@ -1,6 +1,7 @@
package ru.ulstu.is.sbapp.database.model;
import jakarta.persistence.*;
import jakarta.validation.constraints.NotNull;
import java.util.Objects;
@ -10,33 +11,32 @@ public class Song {
@Id
@GeneratedValue
private Long id;
@NotNull(message = "Name can't be empty")
@Column(name = "name")
private String songName;
@NotNull(message = "Duration can't be empty")
@Column(name = "duration")
private Double duration;
@ManyToOne(cascade = {CascadeType.MERGE}, fetch = FetchType.EAGER)
@JoinColumn(name = "album", nullable = true)
private Album album;
private Double Duration;
public Song(){
}
public Song(String songName, Double duration){
public Song(String songName, Double Duration){
this.songName = songName;
this.duration = duration;
this.Duration = Duration;
}
public Long getId(){return id;}
public String getSongName(){
return songName;
}
public Double getSongDuration(){
return duration;
return Duration;
}
public void setSongName(String songName) {
this.songName = songName;
}
public void setSongDuration(Double duration) {
this.duration = duration;
public void setSongDuration(Double Duration) {
this.Duration = Duration;
}
public boolean equals(Object o) {
if (this == o) return true;
@ -44,12 +44,6 @@ public class Song {
Song song = (Song) o;
return Objects.equals(id, song.id);
}
public Album getAlbum(){
return album;
}
public void setAlbum(Album album){
this.album = album;
}
@Override
public int hashCode() {
return Objects.hash(id);
@ -60,7 +54,8 @@ public class Song {
return "Song{" +
"id=" + id +
", songName='" + songName + '\'' +
", duration='" + duration + '\'' +
", Duration='" + Duration + '\'' +
'}';
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.database.service;
public class AlbumNotFoundException extends RuntimeException{
public AlbumNotFoundException(Long id){
super(String.format("Album with id [%s] is not found", id));
}
}

View File

@ -2,132 +2,83 @@ package ru.ulstu.is.sbapp.database.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.Repository.IAlbumRepository;
import ru.ulstu.is.sbapp.controllers.AlbumDTO;
import ru.ulstu.is.sbapp.database.model.Album;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.model.Album;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class AlbumService {
@PersistenceContext
private EntityManager em;
private final IAlbumRepository albumRepository;
private final ArtistService artistService;
private final SongService songService;
public AlbumService(IAlbumRepository albumRepository,
ArtistService artistService,
SongService songService
){
this.albumRepository = albumRepository;
this.artistService = artistService;
this.songService = songService;
}
@Transactional
public Album addAlbum(String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Album name is null or empty");
}
final Album album = new Album(name);
em.persist(album);
public Album addAlbum(AlbumDTO albumDTO) {
List<Artist> artists = artistService.findAllArtistsById(albumDTO);
List<Song> songs = songService.findAllSongById(albumDTO);
final Album album = new Album(
albumDTO.getAlbumName(), artists, songs);
albumRepository.save(album);
return album;
}
@Transactional
public Album addSong(Album currentAlbum, List<Song> songs){
for (Song song : songs) {
if (song.getAlbum() != null) {
song.getAlbum().removeSong(song);
}
currentAlbum.addSong(song);
em.merge(song);
}
em.merge(currentAlbum);
public Album addSong(AlbumDTO albumDTO, List<Song> songs){
final Album currentAlbum = findAlbum(albumDTO.getId());
currentAlbum.setSongs(songs);
return currentAlbum;
}
@Transactional
public Album addArtist(Album currentAlbum, List<Artist> artists){
for (Artist artist : artists) {
currentAlbum.addArtist(artist);
}
em.merge(currentAlbum);
public Album addArtist(AlbumDTO albumDTO, List<Artist> artists){
final Album currentAlbum = findAlbum(albumDTO.getId());
currentAlbum.setArtists(artists);
return currentAlbum;
}
@Transactional(readOnly = true)
public Album findAlbum(Long id) {
final Album album = em.find(Album.class, id);
if (album == null) {
throw new EntityNotFoundException(String.format("Album with id [%s] is not found", id));
final Optional<Album> album = albumRepository.findById(id);
return album.orElseThrow(() -> new AlbumNotFoundException(id));
}
return album;
}
@Transactional(readOnly = true)
public List<Album> findAllAlbums() {
return em.createQuery("select s from Album s", Album.class)
.getResultList();
return albumRepository.findAll();
}
@Transactional
public Album updateAlbum(Long id, String name, List<Song> newSongs, List<Artist> newArtists) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Album name is null or empty");
}
public Album updateAlbum(Long id, AlbumDTO albumDTO) {
final Album currentAlbum = findAlbum(id);
currentAlbum.setAlbumName(name);
em.merge(currentAlbum);
if(newSongs != null){
for (Song newSong : newSongs) {
if (!currentAlbum.getSongs().contains(newSong)) {
currentAlbum.addSong(newSong);
}
}
for(int i = 0; i < currentAlbum.getSongs().size(); i++) {
if (!newSongs.contains(currentAlbum.getSongs().get(i))) {
currentAlbum.removeSong(currentAlbum.getSongs().get(i));
}
currentAlbum.setAlbumName(albumDTO.getAlbumName());
}
}
for (Artist newArtist : newArtists) {
if (!currentAlbum.getArtists().contains(newArtist)) {
currentAlbum.addArtist(newArtist);
}
}
for(int i = 0; i < currentAlbum.getArtists().size(); i++){
if(!newArtists.contains(currentAlbum.getArtists().get(i))){
currentAlbum.removeArtist(currentAlbum.getArtists().get(i));
}
}
em.merge(currentAlbum);
List<Artist> newArtists = artistService.findAllArtistsById(albumDTO);
List<Song> newSongs = songService.findAllSongById(albumDTO);
currentAlbum.setArtists(newArtists);
currentAlbum.setSongs(newSongs);
albumRepository.save(currentAlbum);
return currentAlbum;
}
@Transactional
public Album deleteAlbum(Long id) {
final Album currentAlbum = findAlbum(id);
List<Artist> artists = currentAlbum.getArtists();
for (Artist artist : artists) {
Artist temp = artist;
currentAlbum.removeArtist(temp);
}
final List<Song> songs = currentAlbum.getSongs();
for (Song song : songs) {
song.setAlbum(null);
}
em.remove(currentAlbum);
return null;
albumRepository.delete(currentAlbum);
return currentAlbum;
}
@Transactional
public void deleteAllAlbums() {
List<Album> list = em.createQuery("select s from Album s", Album.class).getResultList();
for(int i = 0; i < list.size(); i++){
deleteAlbum(list.get(i).getId());
}
em.createQuery("update Song s SET s.album = null ").executeUpdate();
em.createQuery("delete from Album").executeUpdate();
}
@Transactional
public List<Album> findFilteredAlbum(Long[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array id is empty");
}
List<Album> albumList = new ArrayList<>();
for (Long aLong : arr) {
albumList.add(em.find(Album.class, aLong));
}
return albumList;
albumRepository.deleteAll();
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.database.service;
public class ArtistNotFoundException extends RuntimeException{
public ArtistNotFoundException(Long id){
super(String.format("Artist with id [%s] is not found", id));
}
}

View File

@ -2,91 +2,75 @@ package ru.ulstu.is.sbapp.database.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.Repository.IArtistRepository;
import ru.ulstu.is.sbapp.controllers.AlbumDTO;
import ru.ulstu.is.sbapp.controllers.ArtistDTO;
import ru.ulstu.is.sbapp.database.model.Album;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.model.Album;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class ArtistService {
@PersistenceContext
private EntityManager em;
@Transactional
public Artist addArtist(String name, String genre) {
if (!StringUtils.hasText(name) || !StringUtils.hasText(genre)) {
throw new IllegalArgumentException("Artist name and genre are null or empty");
private final IArtistRepository artistRepository;
public ArtistService(IArtistRepository artistRepository){
this.artistRepository = artistRepository;
}
final Artist artist = new Artist(name, genre);
em.persist(artist);
@Transactional
public Artist addArtist(ArtistDTO artistDTO) {
Artist artist =new Artist(artistDTO.getArtistName(), artistDTO.getGenre());
artistRepository.save(artist);
return artist;
}
@Transactional(readOnly = true)
public Artist findArtist(Long id) {
final Artist artist = em.find(Artist.class, id);
if (artist == null) {
throw new EntityNotFoundException(String.format("Artist with id [%s] is not found", id));
}
return artist;
final Optional<Artist> artist = artistRepository.findById(id);
return artist.orElseThrow(()->new ArtistNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Artist> findAllArtists() {
return em.createQuery("select s from Artist s", Artist.class)
.getResultList();
return artistRepository.findAll();
}
@Transactional(readOnly = true)
public List<Artist> findFilteredArtist(Long[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array id is empty");
}
List<Artist> artistsList = new ArrayList<>();
for (int i = 0; i < arr.length; i++) {
artistsList.add(em.find(Artist.class, arr[i]));
}
return artistsList;
public List<Artist> findAllArtistsById(AlbumDTO albumDTO) {
return artistRepository
.findAllById(albumDTO
.getArtistDTOList()
.stream()
.map(x -> x.getId())
.toList());
}
@Transactional
public Artist updateArtist(Long id, String name, String genre) {
if (!StringUtils.hasText(name) || !StringUtils.hasText(genre)) {
throw new IllegalArgumentException("Artist name and genre is null or empty");
}
public Artist updateArtist(Long id, ArtistDTO artistDTO) {
final Artist currentArtist = findArtist(id);
currentArtist.setArtistName(name);
currentArtist.setGenre(genre);
em.merge(currentArtist);
currentArtist.setArtistName(artistDTO.getArtistName());
currentArtist.setGenre(artistDTO.getGenre());
artistRepository.save(currentArtist);
return currentArtist;
}
@Transactional
public Artist deleteArtist(Long id) {
final Artist currentArtist = findArtist(id);
final Artist currentArtist= findArtist(id);
int size = currentArtist.getAlbum().size();
for (int i = 0; i < size; i++) {
Album temp = currentArtist.getAlbum().get(i);
temp.removeArtist(currentArtist);
currentArtist.removeAlbum(temp);
em.remove(temp);
}
em.remove(currentArtist);
artistRepository.delete(currentArtist);
return currentArtist;
}
@Transactional
public List<Song> findAllSongsProducedArtist(Artist currentArtist){
if(currentArtist.getAlbum().size() == 0){
throw new IllegalArgumentException("Artist doesn`t produced");
}
List songList = em.createQuery("SELECT DISTINCT a.songs FROM Album a where :artistAlbum MEMBER OF a.artists")
.setParameter("artistAlbum", currentArtist).getResultList();
return songList;
public List<Song> findAllSongsProducedArtist(Long id){
return artistRepository.getSongs(findArtist(id));
}
@Transactional
public void deleteAllArtists() {
em.createQuery("delete from Artist").executeUpdate();
artistRepository.deleteAll();
}
}

View File

@ -0,0 +1,7 @@
package ru.ulstu.is.sbapp.database.service;
public class SongNotFoundException extends RuntimeException {
public SongNotFoundException(Long id){
super(String.format("Song with id [%s] is not found", id));
}
}

View File

@ -2,86 +2,70 @@ package ru.ulstu.is.sbapp.database.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.Repository.ISongRepository;
import ru.ulstu.is.sbapp.controllers.SongDTO;
import ru.ulstu.is.sbapp.controllers.AlbumDTO;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.model.Album;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@Service
public class SongService {
@PersistenceContext
private EntityManager em;
@Transactional
public Song addSong(String songName, Double duration) {
if (!StringUtils.hasText(songName) || duration <= 0) {
throw new IllegalArgumentException("Song name is null or empty");
private final ISongRepository songRepository;
public SongService(ISongRepository songRepository){
this.songRepository = songRepository;
}
final Song song = new Song(songName, duration);
em.persist(song);
@Transactional
public Song addSong(SongDTO songDTO) {
final Song song = new Song(songDTO.getSongName(), songDTO.getSongDuration());
songRepository.save(song);
return song;
}
@Transactional(readOnly = true)
public Song findSong(Long id) {
final Song song = em.find(Song.class, id);
if (song == null) {
throw new EntityNotFoundException(String.format("Song with id [%s] is not found", id));
final Optional<Song> song = songRepository.findById(id);
return song.orElseThrow(()->new SongNotFoundException(id));
}
return song;
@Transactional(readOnly = true)
public List<Song> findAllSongById(AlbumDTO albumDTO) {
return songRepository
.findAllById(albumDTO
.getSongDTOList()
.stream()
.map(x->x.getId())
.toList());
}
@Transactional(readOnly = true)
public List<Song> findAllSongs() {
return em.createQuery("select s from Song s", Song.class)
.getResultList();
return songRepository
.findAll();
}
@Transactional
public Song updateSong(Long id, String songName, Double duration, Album album) {
if (!StringUtils.hasText(songName) || duration <= 0) {
throw new IllegalArgumentException("Song name is null or empty");
}
public Song updateSong(Long id, SongDTO song) {
final Song currentSong = findSong(id);
currentSong.setSongName(songName);
currentSong.setSongDuration(duration);
currentSong.setAlbum(album);
em.merge(currentSong);
currentSong.setSongName(song.getSongName());
currentSong.setSongDuration(song.getSongDuration());
songRepository.save(currentSong);
return currentSong;
}
@Transactional
public Song deleteSong(Long id) {
final Song currentSong= findSong(id);
if(currentSong.getAlbum() != null) currentSong.getAlbum().removeSong(currentSong);
em.remove(currentSong);
final Song currentSong = findSong(id);
songRepository.delete(currentSong);
return currentSong;
}
@Transactional(readOnly = true)
public List<Song> findFilteredSongs(Long[] arr) {
if (arr.length == 0) {
throw new IllegalArgumentException("Array id is empty");
}
List<Song> songList = new ArrayList<>();
for (Long aLong : arr) {
songList.add(em.find(Song.class, aLong));
}
return songList;
}
@Transactional
public List findSongsInAlbum(Song currentSong){
if(currentSong.getAlbum() == null){
throw new IllegalArgumentException("Album is empty");
}
return em.createQuery("SELECT s.songs FROM Album s where s.id = :songAlbum")
.setParameter("songAlbum", currentSong.getAlbum().getId()).getResultList();
public List<Song> findSongsInAlbum(Long id){
return songRepository.findSongsInAlbum(findSong(id));
}
@Transactional
public void deleteAllSongs() {
em.createQuery("delete from Song").executeUpdate();
songRepository.deleteAll();
}
}

View File

@ -1,118 +1,4 @@
package ru.ulstu.is.sbapp;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.model.Album;
import ru.ulstu.is.sbapp.database.service.ArtistService;
import ru.ulstu.is.sbapp.database.service.SongService;
import ru.ulstu.is.sbapp.database.service.AlbumService;
import jakarta.persistence.*;
import java.util.ArrayList;
import java.util.List;
@SpringBootTest
public class SbappApplicationTests {
@Autowired
private AlbumService albumService;
@Autowired
private SongService songService;
@Autowired
private ArtistService artistService;
@Test
void test1(){
albumService.deleteAllAlbums();
artistService.deleteAllArtists();
songService.deleteAllSongs();
final Song song = songService.addSong("song", 2.50);
Assertions.assertNotNull(song.getId());
Song song2 = songService.addSong("song2", 3.10);
List<Song> songs = new ArrayList<>();
songs.add(song);
songs.add(song2);
Artist artist = artistService.addArtist("artist", "genre");
Assertions.assertNotNull(artist.getId());
Artist artist2 = artistService.addArtist("artist2", "genre");
List<Artist> artists = new ArrayList<>();
artists.add(artist);
artists.add(artist2);
Album album = albumService.addAlbum("album");
Album album2 = albumService.addAlbum("album2");
Assertions.assertNotNull(album.getId());
albumService.addArtist(album, artists);
albumService.addSong(album, songs);
artist2 = artistService.updateArtist(artist2.getId(), "artist3", "genre2");
Assertions.assertEquals("artist3", artistService.findArtist(artist2.getId()).getArtistName());
song2 = songService.updateSong(song2.getId(), "song3", 3.40, null);
Assertions.assertEquals("song3", songService.findSong(song2.getId()).getSongName());
album = albumService.updateAlbum(album.getId(), "album3", songs, artists);
Assertions.assertEquals("album3", albumService.findAlbum(album.getId()).getAlbumName());
Assertions.assertEquals(true, artistService.findAllSongsProducedArtist(artist).contains(song));
Assertions.assertEquals(true, songService.findSongsInAlbum(song).contains(song2));
final Song findSong = songService.findSong(song.getId());
Assertions.assertEquals(song, findSong);
final Artist findArtist = artistService.findArtist(artist.getId());
Assertions.assertEquals(artist, findArtist);
final Album findAlbum = albumService.findAlbum(album.getId());
Assertions.assertEquals(album, findAlbum);
//TestReadAll
final List<Song> songss = songService.findAllSongs();
Assertions.assertEquals(songss.size(), 2);
final List<Artist> artistss = artistService.findAllArtists();
Assertions.assertEquals(artistss.size(), 2);
final List<Album> albumss = albumService.findAllAlbums();
Assertions.assertEquals(albumss.size(), 2);
//TestReadNotFound
//album2 = albumService.updateAlbum(album2.getId(), "стул",songs, artistService.findAllArtists());
//albumService.deleteAlbum(album.getId());
//albumService.deleteAlbum(album2.getId());
List<Song> list = songService.findAllSongs();
List<Artist> list2 = artistService.findAllArtists();
albumService.deleteAllAlbums();
songService.deleteAllSongs();
artistService.deleteAllArtists();
Assertions.assertThrows(EntityNotFoundException.class, () -> songService.findSong(-1L));
Assertions.assertThrows(EntityNotFoundException.class, () -> artistService.findArtist(-1L));
Assertions.assertThrows(EntityNotFoundException.class, () -> albumService.findAlbum(-1L));
//TestReadAllEmpty
final List<Song> newComponents = songService.findAllSongs();
Assertions.assertEquals(newComponents.size(), 0);
final List<Album> newOrders = albumService.findAllAlbums();
Assertions.assertEquals(newOrders.size(), 0);
final List<Artist> newArtists = artistService.findAllArtists();
Assertions.assertEquals(newArtists.size(), 0);
}
}