Compare commits

...

2 Commits

Author SHA1 Message Date
7a49635284 lab4 2023-06-09 19:39:46 +04:00
2edfbc3238 lab4 2023-06-01 23:20:18 +04:00
29 changed files with 1314 additions and 601 deletions

View File

@ -1,137 +0,0 @@
<template>
<div v-if="currentAlbum" class="edit-form">
<h4>Album</h4>
<form>
<div class="form-group">
<label for="albumName">Album Name</label>
<input type="text" class="form-control" id="albumName"
v-model="currentAlbum.albumName"
/>
</div>
<div class="form-group">
<label >Song</label>
<div>
<select v-model="currentAlbum.song">
<option v-for="blog in songs" :key="blog.id" :value="blog">{{ blog.nickName }}</option>
</select>
</div>
</div>
<div class="form-group prokrutka">
<label >Artists</label>
<div>
<template v-for="art in artists" v-bind:key="art.id">
<input type="checkbox" v-bind:value="art" v-model="currentAlbum.artistList"/>
<label>{{ art.albumName }}</label><br/>
</template>
</div>
</div>
</form>
<button class="badge badge-danger mr-2"
@click="deleteAlbum"
>
Delete
</button>
<button type="submit" class="badge badge-success"
@click="updateAlbum"
>
Update
</button>
<p>{{ message }}</p>
</div>
<div v-else>
<br />
<p>Please click on a Album...</p>
</div>
</template>
<style>
.prokrutka {
height: 200px;
width: 100%;
background: #fff;
border: 1px solid #C1C1C1;
overflow-x: hidden;
overflow-y:scroll;
}
</style>
<script>
import AlbumDataService from '../services/AlbumDataService';
import ArtistDataService from '../services/ArtistDataService';
import SongDataService from '../services/SongDataService';
export default {
name: "album",
data() {
return {
currentAlbum: null,
artists : [],
songs : [],
message: ''
};
},
created() {
ArtistDataService.getAll()
.then(response => {
this.artists = response.data;
console.log(response.data);
});
SongDataService.getAll()
.then(response => {
this.songs = response.data;
console.log(response.data);
}
);
},
methods: {
getAlbum(id) {
AlbumDataService.get(id)
.then(response => {
this.currentAlbum = response.data;
console.log(response.data);
})
.artch(e => {
console.log(e);
});
},
updateAlbum() {
AlbumDataService.update(this.currentAlbum.id, this.currentAlbum)
.then(response => {
console.log(response.data);
this.message = 'The album was updated successfully!';
})
.artch(e => {
console.log(e);
});
},
deleteAlbum() {
AlbumDataService.delete(this.currentAlbum.id)
.then(response => {
console.log(response.data);
this.$router.push({ name: "albums" });
})
.artch(e => {
console.log(e);
});
}
},
mounted() {
this.message = '';
this.getAlbum(this.$route.params.id);
}
};
</script>
<style>
.edit-form {
max-width: 300px;
margin: auto;
}
</style>

View File

@ -1,25 +0,0 @@
import axios from "../http-common";
class AlbumDataService {
getAll() {
return axios.get( "/albums");
}
get(id) {
return axios.get( `/albums/${id}`);
}
create(data) {
return axios.post( `/albums`, data);
}
update(id, data) {
return axios.put(`/albums/${id}`, data);
}
delete(id) {
return axios.delete(`/albums/${id}`);
}
}
export default new AlbumDataService();

View File

@ -1,25 +0,0 @@
import axios from "../http-common";
class ArtistDataService {
getAll() {
return axios.get( "/artists");
}
get(id) {
return axios.get( `/artists/${id}`);
}
create(data) {
return axios.post( `/artists`, data);
}
update(id, data) {
return axios.put(`/artists/${id}`, data);
}
delete(id) {
return axios.delete(`/artists/${id}`);
}
}
export default new ArtistDataService();

View File

@ -1,25 +0,0 @@
import axios from "../http-common";
class SongDataService {
getAll() {
return axios.get( "/songs");
}
get(id) {
return axios.get( `/songs/${id}`);
}
create(data) {
return axios.post( `/songs`, data);
}
update(id, data) {
return axios.put(`/songs/${id}`, data);
}
delete(id) {
return axios.delete(`/songs/${id}`);
}
}
export default new SongDataService();

View File

@ -1,50 +0,0 @@
{
"name": "front",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^1.4.0",
"bootstrap": "^4.6.0",
"core-js": "^3.8.3",
"jquery": "^3.6.4",
"popper.js": "^1.16.1",
"vue": "^3.2.13",
"vue-router": "^4.1.6"
},
"devDependencies": {
"@babel/core": "^7.12.16",
"@babel/eslint-parser": "^7.12.16",
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"eslint": "^7.32.0",
"eslint-plugin-vue": "^8.0.3"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "@babel/eslint-parser"
},
"rules": {
"vue/multi-word-component-names": 0
}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead",
"not ie 11"
]
}

View File

@ -0,0 +1,48 @@
<template>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav justify-content-center">
<li class="nav-item">
<router-link to="/songs" class="nav-link">Песни</router-link>
</li>
<li class="nav-item">
<router-link to="/albums" class="nav-link">Альбомы</router-link>
</li>
<li class="nav-item">
<router-link to="/artists" class="nav-link">Исполнители</router-link>
</li>
</ul>
</div>
</div>
</nav>
</template>
<style>
.navbar-brand {
font-size: 2rem;
font-weight: bold;
}
.nav-link {
color: black;
font-weight: bold;
transition: color 0.3s ease-in-out;
}
.nav-link:hover {
color: white;
}
.nav-link {
color: grey;
}
</style>
<script>
export default {
}
</script>

View File

@ -0,0 +1,7 @@
export default class Album{
constructor(data) {
this.id = data?.id;
this.albumName = data?.albumName;
this.artistIds = data?.artistIds;
}
}

View File

@ -0,0 +1,7 @@
export default class Artist{
constructor(data) {
this.id = data?.id;
this.artistName = data?.artistName;
this.albumIds = data?.albumIds;
}
}

8
front/src/models/Song.js Normal file
View File

@ -0,0 +1,8 @@
export default class Song{
constructor(data) {
this.id = data?.id;
this.songName = data?.songName;
this.duration = data?.duration;
this.album = data?.album;
}
}

408
front/src/pages/albums.vue Normal file
View File

@ -0,0 +1,408 @@
<template>
<div class="container mt-4">
<h1 class="text-center mb-4">Альбомы</h1>
<button class="btn btn-primary mr-2" @click="openModal('create')">Добавить</button>
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>Название</th>
<th>Альбомы</th>
<th>Исполнители</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="alb in albums" :key="alb.id">
<td>{{ alb.albumName }}</td>
<td>
<div class="d-flex flex-column">
<button class="btn btn-primary mb-2" @click="OpenModelForSongs(); getSongsFromAlbum(alb.id)">Просмотр песен</button>
<button class="btn btn-primary mb-2" @click="OpenModelForAddSongs(alb); getSongsFromUndefinedAlbum()">Добавить песен в альбом</button>
</div>
</td>
<td>
<div class="d-flex flex-column">
<button class="btn btn-primary mb-2" @click="OpenModelForArtists(); getArtistsInAlbum(alb.id)">Просмотр исполнителей</button>
<button class="btn btn-primary mb-2" @click="OpenModelForAddArtists('edit', alb);">Добавить исполнителей в альбом</button>
</div>
</td>
<td>
<div class="d-flex flex-column">
<button class="btn btn-primary mb-2" @click="openModal('edit', alb)">Изменить</button>
<button class="btn btn-danger mb-2" @click="deleteAlbum(alb.id)">Удалить</button>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!--Форма для привязки артиста и альбомов -->
<div class="modal" tabindex="-1" id="openModalForAddArtists">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Добавить исполнителей</h5>
</div>
<div class="modal-body">
<form>
<div class="form-album">
<label for="albumName">Имя:</label>
<input readonly type="text" class="form-control" id="albumName" name="albumName" v-model="album.albumName">
</div>
<div class="form-album">
<label for="name">Выберите исполнителей:</label>
<ul class="list-album">
<li class="list-album-item" v-for="artist in artists" :key="artist.id">
<div class="form-check">
<input class="form-check-input" type="checkbox" v-model="selectedArtists" :value="artist.id" v-bind:checked="open.includes(artist.id)" id="albumCheck{{ artist.id }}">
<label class="form-check-label" for="albumCheck{{ artist.id }}">{{ artist.artistName }}</label>
</div>
</li>
</ul>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModalForAddArtists()">Закрыть</button>
<button type="button" class="btn btn-primary" @click="addArtistToAlbum(album.id, selectedArtists)">Добавить</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно песен в альбом-->
<div class="modal" tabindex="-1" id="ModalForAddSongs">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Добавить песни</h5>
</div>
<div class="modal-body">
<form>
<div class="form-album">
<label for="albumName">Название:</label>
<input type="text" class="form-control" id="albumName" name="albumName" v-model="album.albumName">
</div>
<div class="form-album">
<label for="name">Выберите песни:</label>
<ul class="list-album">
<li class="list-album-item" v-for="song in songs" :key="song.id">
<div class="form-check">
<input class="form-check-input" type="checkbox" :id="'songCheck' + song.id" :value="song.id" v-model="selectedSongs">
<label class="form-check-label" :for="'songCheck' + song.id">{{ song.songName }}</label>
</div>
</li>
</ul>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="CloseModalForAddSongs()">Закрыть</button>
<button type="button" class="btn btn-primary" @click="saveSongs(album.id)">Сохранить</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно и изменения-->
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Альбом</h5>
</div>
<div class="modal-body">
<form>
<div class="form-album">
<label for="albumName">Название:</label>
<input type="text" class="form-control" id="albumName" name="albumName" v-model="album.albumName">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="album.status === 'create'" @click="addAlbum(album)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editAlbum(album)">Сохранить</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно для просмотра песен в альбоме-->
<div class="modal" tabindex="-1" id="ModelForSongs">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Песни</h5>
</div>
<div class="modal-body">
<form>
<div class="form-album">
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>Название</th>
<th>Продолжительность</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="son in songs" :key="son.id">
<td>{{ son.songName }}</td>
<td>{{ son.duration }}</td>
<td>
<td>
<button class="btn btn-danger mr-2" @click="deleteSongFromAlbum(son.id)">Удалить</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="ModelForSongs" @click="closeModelForSongs()">Закрыть</button>
</div>
</div>
</div>
</div>
<!-- Модальное окно для просмотра исполнителей в альбомове-->
<div class="modal" tabindex="-1" id="ModelForArtists">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Исполнители</h5>
</div>
<div class="modal-body">
<form>
<div class="form-album">
<table class="thead-inverse table table-striped">
<thead>
<tr>
<th>Имя</th>
</tr>
</thead>
<tbody>
<tr v-for="art in artistsInAlbum" :key="art.id">
<td>{{ art.artistName }}</td>
</tr>
</tbody>
</table>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="ModelForArtists" @click="closeModelForArtists()">Закрыть</button>
</div>
</div>
</div>
</div>
</template>
<script>
import 'axios';
import axios from "axios";
import Album from "@/models/Album";
import Song from "@/models/Song";
import Artist from "@/models/Artist";
export default {
created() {
this.getAlbums();
this.getArtists();
this.getAll();
},
data() {
return{
albums: [],
URL: "http://localhost:8080/",
album: new Album(),
songs: [],
artists: [],
selectedSongs: [],
open: [],
albumId: undefined,
selectedArtists: [],
artistsInAlbum: [],
getAllInfo: new Object() ,
}
},
methods: {
getAll(){
axios.get(this.URL + "album/getAll")
.then(response => {
this.getAllInfo = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getArtistsInAlbum(id){
axios.get(this.URL + `album/${id}/getAllArtists`)
.then(response => {
this.artistsInAlbum = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getAlbums(){
axios.get(this.URL + "album")
.then(response => {
this.albums = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addAlbum(album){
console.log(this.album);
axios.post(this.URL + "album", album)
.then(() => {
this.getAlbums();
this.closeModal();
})
.catch(error => {
console.log(error);
});
},
deleteAlbum(id){
axios.delete(this.URL + `album/${id}`)
.then(() =>{
this.getAlbums();
})
},
editAlbum(album){
axios.put(this.URL + `album/${album.id}`, album)
.then(() =>{
const index = this.albums.findIndex((s) => s.id === album.id);
if (index !== -1) {
this.albums[index] = { ...album };
}
this.closeModal();
this.getAlbums();
})
this.closeModal();
},
openModal(status, album = null) {
if (status === "create") {
this.album = new Album();
this.album.status = "create";
} else if (status === "edit" && album) {
this.album = { ...album };
this.album.status = "edit";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
getSongsFromAlbum(albumId){
this.selectedSongs = [];
axios.get(this.URL + `album/${albumId}/songs`)
.then(response => {
this.songs = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
OpenModelForSongs() {
document.getElementById("ModelForSongs").style.display = "block";
},
closeModelForSongs() {
document.getElementById("ModelForSongs").style.display = "none";
},
OpenModelForArtists() {
document.getElementById("ModelForArtists").style.display = "block";
},
closeModelForArtists() {
document.getElementById("ModelForArtists").style.display = "none";
},
OpenModelForAddSongs(album) {
this.album = { ...album };
document.getElementById("ModalForAddSongs").style.display = "block";
},
CloseModalForAddSongs() {
document.getElementById("ModalForAddSongs").style.display = "none";
},
saveSongs(id) {
axios.post(this.URL + `album/${id}/addSongs`, this.selectedSongs)
.then(() => {
this.getSongsFromAlbum(id);
this.CloseModalForAddSongs();
console.log(this.songs);
})
.catch(error => {
console.log(error);
});
},
getSongsFromUndefinedAlbum(){
axios.get(this.URL + `album/getSongsUndefined`)
.then(response => {
this.songs = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
deleteSongFromAlbum(id){
axios.delete(this.URL + `album/deleteSongFromAlbum/${id}`)
.then(() =>{
this.getSongsFromAlbum();
})
.catch(error => {
console.log(error);
});
},
OpenModelForAddArtists(status, album = null) {
if (status === "create") {
this.album = new Album();
this.album.status = "create";
} else if (status === "edit" && album) {
this.album = { ...album };
this.album.status = "edit";
}
this.open = this.album.artistIds ? [...this.album.artistIds] : []; // Создаём новый массив, чтобы избежать проблем с ссылками
this.loadSelectedArtists(); // Загрузка выбранных альбомов при открытии модального окна
document.getElementById("openModalForAddArtists").style.display = "block";
},
closeModalForAddArtists() {
document.getElementById("openModalForAddArtists").style.display = "none";
this.open = [...this.selectedArtists]; // Обновление массива open значениями из selectedAlbums
this.selectedArtists = []; // Сброс выбранных альбомов
this.album = new Album(); // Сброс текущего предмета при закрытии модального окна
},
loadSelectedArtists() {
// Загрузка выбранных альбомов из массива open
this.selectedArtists = [...this.open];
},
addArtistToAlbum(id, list) {
axios
.post(this.URL + `album/${id}/addArtistToAlbum`, list)
.then(() => {
this.closeModalForAddArtists();
this.getAlbums(); // Обновляем список исполнителей после успешного добавления
this.open = [...this.selectedArtists]; // Обновляем массив выбранных альбомов
})
.catch((error) => {
console.log(error);
});
},
getArtists(){
axios.get(this.URL + "artist")
.then(response => {
this.artists = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
}
}
</script>
<style>
</style>

130
front/src/pages/artists.vue Normal file
View File

@ -0,0 +1,130 @@
<template>
<div class="container mt-4">
<h1 class="text-center mb-4">Исполнители</h1>
<button class="btn btn-primary mr-2" @click="openModal('create')">Добавить</button>
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>Имя</th>
<th>Жанр</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="art in artists" :key="art.id">
<td>{{ art.artistName }}</td>
<td>{{ art.genre }}</td>
<td>
<td>
<button class="btn btn-primary mr-2" @click="openModal('edit', art)">Изменить</button>
</td>
<td>
<button class="btn btn-danger" @click="deleteArtist(art.id)">Удалить</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
<!--Форма для создания и добавления исполнителей -->
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Исполнитель</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="artistName">Имя:</label>
<input type="text" class="form-control" id="artistName" name="artistName" v-model="artist.artistName">
</div>
<div class="form-group">
<label for="genre">Жанр:</label>
<input type="text" class="form-control" id="genre" name="genre" v-model="artist.genre">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="artist.status === 'create'" @click="addArtist(artist)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editArtist(artist)">Сохранить</button>
</div>
</div>
</div>
</div>
</template>
<script>
import 'axios';
import axios from "axios";
import Artist from "@/models/Artist";
import Album from "@/models/Album";
export default {
created() {
this.getArtists();
},
data() {
return{
artists: [],
URL: "http://localhost:8080/",
artist: new Artist(),
}
},
methods: {
getArtists(){
axios.get(this.URL + "artist")
.then(response => {
this.artists = response.data;
})
.catch(error => {
console.log(error);
});
},
addArtist(artist){
console.log(artist);
axios.post(this.URL + "artist", artist)
.then(() => {
this.getArtists();
this.closeModal();
})
.catch(error => {
console.log(error);
});
},
deleteArtist(id){
axios.delete(this.URL + `artist/${id}`)
.then(() =>{
this.getArtists();
})
},
editArtist(artist){
axios.put(this.URL + `artist/${artist.id}`, artist)
.then(() =>{
const index = this.artists.findIndex((s) => s.id === artist.id);
if (index !== -1) {
this.artists[index] = { ...artist };
}
this.closeModal();
this.getArtists();
})
this.closeModal();
},
openModal(status, artist = null) {
if (status === "create") {
this.artist = new Artist();
this.artist.status = "create";
} else if (status === "edit" && artist) {
this.artist = { ...artist };
this.artist.status = "edit";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
}
}
</script>
<style>
</style>

156
front/src/pages/songs.vue Normal file
View File

@ -0,0 +1,156 @@
<template>
<div class="container mt-4">
<h1 class="text-center mb-4">Песни</h1>
<button class="btn btn-primary mr-2" @click="openModal('create')">Добавить</button>
<table class="table table-striped">
<thead class="thead-inverse">
<tr>
<th>Название</th>
<th>Продолжительность</th>
<th>Альбом</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="son in songs" :key="son.id">
<td>{{ son.songName }}</td>
<td>{{ son.duration }}</td>
<td>{{ son.albumName || 'No Album'}}</td>
<td>
<td>
<button class="btn btn-primary mr-2" @click="openModal('edit', son)">Изменить</button>
</td>
<td>
<button class="btn btn-danger" @click="deleteSong(son.id)">Удалить</button>
</td>
</td>
</tr>
</tbody>
</table>
</div>
<div class="modal" tabindex="-1" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Песня</h5>
</div>
<div class="modal-body">
<form>
<div class="form-group">
<label for="songName">Название:</label>
<input type="text" class="form-control" id="songName" name="songName" v-model="editedSong.songName">
</div>
<div class="form-group">
<label for="duration">Продолжительность:</label>
<input type="number" class="form-control" id="duration" name="duration" step="0.1" v-model="editedSong.duration">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="editModal" @click="closeModal()">Закрыть</button>
<button type="button" class="btn btn-primary" v-if="editedSong.status === 'create'" @click="addSong(editedSong)">Создать</button>
<button type="button" class="btn btn-primary" v-else @click="editSong(editedSong)">Сохранить</button>
</div>
</div>
</div>
</div>
</template>
<script>
import 'axios';
import axios from "axios";
import Song from "@/models/Song";
export default {
created() {
this.getSongs();
this.getAlbums();
},
mounted() {
const addModal = document.getElementById('editModal');
addModal.addEventListener('shown.bs.modal', function () {
})
},
data() {
return{
songs: [],
albums: [],
URL: "http://localhost:8080/",
song: new Song(),
editedSong: new Song(),
}
},
methods: {
getSongs(){
axios.get(this.URL + "song")
.then(response => {
this.songs = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
getAlbums() {
axios.get(this.URL + "song/albums")
.then(response => {
this.albums = response.data;
console.log(response.data);
})
.catch(error => {
console.log(error);
});
},
addSong(song) {
console.log(song);
song.album = null;
console.log(song);
axios
.post(this.URL + "song", song)
.then(() => {
this.getSongs();
this.closeModal();
})
.catch((error) => {
console.log(error);
});
},
deleteSong(id){
axios.delete(this.URL + `song/${id}`)
.then(() =>{
this.getSongs();
})
},
openModal(status, song = null) {
if (status === "create") {
this.editedSong = new Song();
this.editedSong.status = "create";
} else if (status === "edit" && song) {
this.editedSong = { ...song };
this.editedSong.status = "edit";
}
document.getElementById("editModal").style.display = "block";
},
closeModal() {
document.getElementById("editModal").style.display = "none";
},
editSong(song) {
axios.put(this.URL + `song/${song.id}`, song)
.then(() => {
const index = this.songs.findIndex((s) => s.id === song.id);
if (index !== -1) {
this.songs[index] = { ...song };
}
this.closeModal();
this.getSongs();
})
.catch((error) => {
console.log(error);
});
},
}
}
</script>
<style>
</style>

19
front/src/router/index.js Normal file
View File

@ -0,0 +1,19 @@
import artists from "../pages/artists.vue"
import albums from "../pages/albums.vue"
import songs from "../pages/songs.vue"
import {createRouter, createWebHistory} from "vue-router"
const routes = [
{path: '/artists', component: artists},
{path: '/albums', component: albums},
{path: '/songs', component: songs},
]
const router = createRouter({
history: createWebHistory(),
linkActiveClass: 'active',
routes
})
export default router;

View File

@ -0,0 +1,15 @@
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<style>
@media (min-width: 1024px) {
.about {
min-height: 100vh;
display: flex;
align-items: center;
}
}
</style>

View File

@ -0,0 +1,9 @@
<script setup>
import TheWelcome from '../components/TheWelcome.vue'
</script>
<template>
<main>
<TheWelcome />
</main>
</template>

View File

@ -1,7 +1,15 @@
package ru.ulstu.is.sbapp.Repository; package ru.ulstu.is.sbapp.Repository;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import ru.ulstu.is.sbapp.database.model.Album; import ru.ulstu.is.sbapp.database.model.Album;
import java.util.List;
public interface IAlbumRepository extends JpaRepository<Album, Long> { public interface IAlbumRepository extends JpaRepository<Album, Long> {
@Query("select a.albumName as album, s.songName as songs " +
"from Album a " +
"join a.songs s " +
"group by a.id, a.albumName, s.songName")
List<Object[]> getAll();
} }

View File

@ -9,6 +9,6 @@ import ru.ulstu.is.sbapp.database.model.Song;
import java.util.List; import java.util.List;
public interface IArtistRepository extends JpaRepository<Artist, Long> { public interface IArtistRepository extends JpaRepository<Artist, Long> {
@Query("SELECT DISTINCT a.songs FROM Album a where :artist MEMBER OF a.artists") @Query(value = "SELECT * FROM artist_album", nativeQuery = true)
List<Song> getSongs(@Param("artist") Artist artist); List<Object[]> getAllArtistAlbum();
} }

View File

@ -1,55 +1,85 @@
package ru.ulstu.is.sbapp.controllers; package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.service.AlbumService; import ru.ulstu.is.sbapp.database.service.AlbumService;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
@RestController @RestController
@RequestMapping("/album") @RequestMapping("/album")
public class AlbumController { public class AlbumController {
private final AlbumService albumService; private final AlbumService albumService;
@Autowired
public AlbumController(AlbumService albumService){ public AlbumController(AlbumService albumService) {
this.albumService = albumService; this.albumService = albumService;
} }
@GetMapping("/albums/{id}")
public AlbumDTO getAlbum(@PathVariable Long id) { @GetMapping("/{id}")
public AlbumDTO getAlbum(@PathVariable Long id){
return new AlbumDTO(albumService.findAlbum(id)); return new AlbumDTO(albumService.findAlbum(id));
} }
@GetMapping("/albums")
public List<AlbumDTO> getAlbums() { @GetMapping
return albumService.findAllAlbums().stream().map(AlbumDTO::new).toList(); public List<AlbumDTO> getAlbums(){
return albumService.findAllAlbums().stream()
.map(AlbumDTO::new)
.toList();
} }
@PostMapping("/albums")
public ResponseEntity<AlbumDTO> createAlbum(@RequestBody @Valid AlbumDTO albumDTO){ @PostMapping
List<Long> list = new ArrayList<>(); public AlbumDTO createAlbum(@RequestBody @Valid AlbumDTO albumDTO){
for (ArtistDTO art: return new AlbumDTO(albumService.addAlbum(albumDTO.getAlbumName()));
albumDTO.getArtistList()) {
list.add(art.getId());
} }
return new ResponseEntity<>
(new AlbumDTO(albumService.addAlbum @PutMapping("/{id}")
(albumDTO.getAlbumName(),list)), HttpStatus.OK); public AlbumDTO updateAlbum(@PathVariable Long id, @RequestBody @Valid AlbumDTO albumDTO){
return new AlbumDTO(albumService.updateAlbum(id, albumDTO.getAlbumName()));
} }
@PutMapping("/albums/{id}")
public ResponseEntity<AlbumDTO> updateAlbum(@RequestBody @Valid AlbumDTO albumDTO){ @DeleteMapping("/{id}")
List<Long> list = new ArrayList<>();
for (ArtistDTO art:
albumDTO.getArtistList()) {
list.add(art.getId());
}
return new ResponseEntity<>
(new AlbumDTO(albumService.updateAlbum
(albumDTO.getId(), albumDTO.getAlbumName(), list)), HttpStatus.OK);
}
@DeleteMapping("/albums/{id}")
public AlbumDTO deleteAlbum(@PathVariable Long id){ public AlbumDTO deleteAlbum(@PathVariable Long id){
return new AlbumDTO(albumService.deleteAlbum(id)); return new AlbumDTO(albumService.deleteAlbum(id));
} }
@GetMapping("/{albumId}/songs")
public ResponseEntity<List<Song>> getSongsFromAlbum(@PathVariable Long albumId) {
List<Song> songs = albumService.getSongFromAlbum(albumId);
return ResponseEntity.ok(songs);
}
@GetMapping("/{albumId}/getAllArtists")
public ResponseEntity<List<Artist>> getArtistInAlbum(@PathVariable Long albumId){
List<Artist> artists = albumService.getArtistInAlbum(albumId);
return ResponseEntity.ok(artists);
}
@GetMapping("/getSongsUndefined")
public ResponseEntity<List<Song>> getSongsFromUndefinedAlbum(){
List<Song> songs = albumService.getSongsUndefined();
return ResponseEntity.ok(songs);
}
@PostMapping("/{id}/addSongs")
public void addSongToAlbum(@PathVariable Long id, @RequestBody @Valid List<Long> songsIds){
albumService.addSongToAlbum(id, songsIds);
}
@DeleteMapping("deleteSongFromAlbum/{id}")
public void deleteSongFromAlbum(@PathVariable Long id){
albumService.deleteSongFromAlbum(id);
}
@PostMapping("/{id}/addArtistToAlbum")
public void addArtistToAlbum(@PathVariable Long id, @RequestBody @Valid List<Long> artistIds){
albumService.addArtistToAlbum(id, artistIds);
}
@GetMapping("/getAll")
public Map<String, List<String>> getAll(){
return albumService.getAll();
}
} }

View File

@ -1,41 +1,38 @@
package ru.ulstu.is.sbapp.controllers; package ru.ulstu.is.sbapp.controllers;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import ru.ulstu.is.sbapp.database.model.Album; import ru.ulstu.is.sbapp.database.model.Album;
import java.util.List; import java.util.List;
public class AlbumDTO { public class AlbumDTO {
@NotNull(message = "Id can't be null") private Long id;
private final Long id; private String albumName;
@NotBlank(message = "Name can't be null or empty") private List<Long> artistIds;
private final String albumName; public AlbumDTO(){
@Null
private final List<ArtistDTO> artistList; }
public AlbumDTO(Album album){ public AlbumDTO(Album album){
this.id = album.getId(); this.id = album.getId();
this.albumName = album.getAlbumName(); this.albumName = album.getAlbumName();
this.artistList = album.getArtists().stream().map(ArtistDTO::new).toList(); this.artistIds = album.getArtistIds();
} }
public AlbumDTO(Long id, String albumName, List<ArtistDTO> artistList){
this.id = id; public Long getId(){
this.albumName = albumName;
this.artistList = artistList;
}
public Long getId() {
return id; return id;
} }
public String getAlbumName(){ public String getAlbumName(){
return albumName; return albumName;
} }
public List<ArtistDTO> getArtistList(){
return artistList; public void setId(Long id){
this.id = id;
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getData() { public void setAlbumName(String name){
return String.format("%s %s %s", id, albumName, artistList.toString()); this.albumName = name;
}
public List<Long> getArtistIds(){
return artistIds;
} }
} }

View File

@ -1,9 +1,6 @@
package ru.ulstu.is.sbapp.controllers; package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.database.service.ArtistService; import ru.ulstu.is.sbapp.database.service.ArtistService;
@ -13,32 +10,45 @@ import java.util.List;
@RequestMapping("/artist") @RequestMapping("/artist")
public class ArtistController { public class ArtistController {
private final ArtistService artistService; private final ArtistService artistService;
@Autowired
public ArtistController(ArtistService artistService){ public ArtistController(ArtistService artistService) {
this.artistService = artistService; this.artistService = artistService;
} }
@GetMapping("/artists/{id}")
public ArtistDTO getArtist(@PathVariable Long id) { @GetMapping("/{id}")
public ArtistDTO getArtist(@PathVariable Long id){
return new ArtistDTO(artistService.findArtist(id)); return new ArtistDTO(artistService.findArtist(id));
} }
@GetMapping("/artists")
public List<ArtistDTO> getArtists() { @GetMapping
public List<ArtistDTO> getArtist(){
return artistService.findAllArtists().stream() return artistService.findAllArtists().stream()
.map(ArtistDTO::new) .map(ArtistDTO::new)
.toList(); .toList();
} }
@PostMapping("/artists")
public ResponseEntity<ArtistDTO> createArtist(@RequestBody @Valid ArtistDTO artistDTO) { @PostMapping
return new ResponseEntity<>(new ArtistDTO(artistService.addArtist(artistDTO.getArtistName(), artistDTO.getGenre())), HttpStatus.OK); public ArtistDTO createArtist(@RequestBody @Valid ArtistDTO artistDTO){
return new ArtistDTO(artistService.addArtist(artistDTO.getArtistName(), artistDTO.getGenre()));
} }
@PutMapping("/artists/{id}") @PutMapping("/{id}")
public ResponseEntity<ArtistDTO> updateArtist(@RequestBody @Valid ArtistDTO artistDTO) { public ArtistDTO updateArtist(@PathVariable Long id, @RequestBody @Valid ArtistDTO artistDTO){
return new ResponseEntity<>(new ArtistDTO(artistService.updateArtist(artistDTO.getId(), artistDTO.getArtistName(), artistDTO.getGenre())), HttpStatus.OK); return new ArtistDTO(artistService.updateArtist(id, artistDTO.getArtistName(), artistDTO.getGenre()));
} }
@DeleteMapping("/artists/{id}") @DeleteMapping("/{id}")
public ArtistDTO deleteArtist(@PathVariable Long id) { public ArtistDTO deleteArtist(@PathVariable Long id){
return new ArtistDTO(artistService.deleteArtist(id)); return new ArtistDTO(artistService.deleteArtist(id));
} }
@GetMapping("/getAllArtistAlbum")
public List<Object[]> getAllArtistAlbum(){
return artistService.getAllArtistAlbum();
}
@PostMapping("/{id}/addArtistToAlbum")
public void addArtistToAlbum(@PathVariable Long id, @RequestBody @Valid List<Long> groupsIds){
artistService.addArtistToAlbum(id, groupsIds);
}
} }

View File

@ -1,35 +1,45 @@
package ru.ulstu.is.sbapp.controllers; package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import ru.ulstu.is.sbapp.database.model.Artist; import ru.ulstu.is.sbapp.database.model.Artist;
import java.util.List; import java.util.List;
public class ArtistDTO { public class ArtistDTO {
@NotNull(message = "Id can't be null") private Long id;
private final Long id; private String artistName;
@NotBlank(message = "Name can't be null or empty") private String genre;
private final String artistName; private List<Long> albumIds;
@NotBlank(message = "Genre can't be null or empty") public ArtistDTO(){
private final String genre;
}
public ArtistDTO(Artist artist){ public ArtistDTO(Artist artist){
this.id = artist.getId(); this.id = artist.getId();
this.artistName = artist.getArtistName(); this.artistName = artist.getArtistName();
this.genre = artist.getGenre(); this.genre = artist.getGenre();
this.albumIds = artist.getAlbumIds();
} }
public ArtistDTO(Long id, String artistName, String genre) {
this.id = id; public Long getId(){
this.artistName = artistName;
this.genre = genre;
}
public Long getId() {
return id; return id;
} }
public String getArtistName() { public void setId(Long id){
this.id = id;
}
public String getArtistName(){
return artistName; return artistName;
} }
public String getGenre() {
public String getGenre(){
return genre; return genre;
} }
public void setGenre(String genre){
this.genre = genre;
}
public List<Long> getAlbumIds(){
return albumIds;
}
} }

View File

@ -1,10 +1,8 @@
package ru.ulstu.is.sbapp.controllers; package ru.ulstu.is.sbapp.controllers;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import ru.ulstu.is.sbapp.database.service.AlbumService;
import ru.ulstu.is.sbapp.database.service.SongService; import ru.ulstu.is.sbapp.database.service.SongService;
import java.util.List; import java.util.List;
@ -13,34 +11,45 @@ import java.util.List;
@RequestMapping("/song") @RequestMapping("/song")
public class SongController { public class SongController {
private final SongService songService; private final SongService songService;
@Autowired private final AlbumService albumService;
public SongController(SongService songService){
public SongController(SongService songService, AlbumService albumService) {
this.songService = songService; this.songService = songService;
this.albumService = albumService;
} }
@GetMapping("/songs/{id}")
public SongDTO getSong(@PathVariable Long id) { @GetMapping("/{id}")
public SongDTO getSong(@PathVariable Long id){
return new SongDTO(songService.findSong(id)); return new SongDTO(songService.findSong(id));
} }
@GetMapping("/songs")
public List<SongDTO> getSongs() { @GetMapping
public List<SongDTO> getSongs(){
return songService.findAllSongs().stream() return songService.findAllSongs().stream()
.map(SongDTO::new) .map(SongDTO::new)
.toList(); .toList();
} }
@PostMapping("/songs")
public ResponseEntity<SongDTO> createSong(@RequestBody @Valid SongDTO songDTO) { @PostMapping
return new ResponseEntity<> public SongDTO createSong(@RequestBody @Valid SongDTO songDTO){
(new SongDTO(songService.addSong return new SongDTO(songService.addSong(songDTO.getSongName(), songDTO.getDuration()));
(songDTO.getSongName(), songDTO.getDuration(), songDTO.getAlbum().getId())), HttpStatus.OK);
} }
@PutMapping("/song/{id}") @PutMapping("/{id}")
public ResponseEntity<SongDTO> updateSong(@RequestBody @Valid SongDTO songDTO) { public SongDTO updateSong(@PathVariable Long id, @RequestBody @Valid SongDTO songDTO) {
return new ResponseEntity<>(new SongDTO(songService.updateSong(songDTO.getId(), songDTO.getSongName(), songDTO.getDuration(), songDTO.getAlbum().getId())), HttpStatus.OK); return new SongDTO(songService.updateSong(id, songDTO.getSongName(), songDTO.getDuration()));
} }
@DeleteMapping("/songs/{id}") @DeleteMapping("/{id}")
public SongDTO deleteSong(@PathVariable Long id) { public SongDTO deleteSong(@PathVariable Long id){
return new SongDTO(songService.deleteSong(id)); return new SongDTO(songService.deleteSong(id));
} }
@GetMapping("/albums")
public List<AlbumDTO> getAlbums() {
return albumService.findAllAlbums().stream()
.map(AlbumDTO::new)
.toList();
}
} }

View File

@ -1,45 +1,57 @@
package ru.ulstu.is.sbapp.controllers; package ru.ulstu.is.sbapp.controllers;
import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import ru.ulstu.is.sbapp.database.model.Song; import ru.ulstu.is.sbapp.database.model.Song;
public class SongDTO { public class SongDTO {
@NotNull(message = "Id can't be null") private Long id;
private final Long id; private String songName;
@NotBlank(message = "Name can't be null or empty") private Double duration;
private final String songName; private Long albumId;
@NotNull(message = "Album can't be null") private String albumName;
private final AlbumDTO album;
@NotBlank(message = "Duration can't be null or empty") public SongDTO() {
private final Double duration; }
public SongDTO(Song song){ public SongDTO(Song song) {
this.id = song.getId(); this.id = song.getId();
this.songName = song.getSongName(); this.songName = song.getSongName();
this.duration = song.getDuration(); this.duration = song.getDuration();
this.album = new AlbumDTO(song.getAlbum()); if(song.getAlbum() != null){
this.albumName = song.getAlbum().getAlbumName();
} }
public SongDTO(Long id, String songName, Double duration, AlbumDTO album){
this.id = id;
this.songName = songName;
this.duration = duration;
this.album = album;
} }
public Long getId() {
public String getAlbumName() {
return albumName;
}
public Long getId(){
return id; return id;
} }
public String getSongName(){ public String getSongName(){
return songName; return songName;
} }
public Double getDuration(){ public Double getDuration(){
return duration; return duration;
} }
public AlbumDTO getAlbum() {
return album; public Long getAlbumId(){
return albumId;
} }
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public String getData() { public void setAlbumId(long id){
return String.format("%s %s %s %s", id, songName, duration, album.getAlbumName()); this.albumId = id;
}
public void setId(long id){
this.id = id;
}
public void setSongName(String name){
this.songName = name;
}
public void setDuration(Double duration){
this.duration = duration;
} }
} }

View File

@ -1,93 +1,52 @@
package ru.ulstu.is.sbapp.database.model; package ru.ulstu.is.sbapp.database.model;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
@Table(name = "albums")
public class Album { public class Album {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@NotBlank
private String albumName; private String albumName;
@OneToMany(fetch = FetchType.EAGER,mappedBy = "album")
@JsonManagedReference
@OneToMany(fetch = FetchType.EAGER, mappedBy = "album")
private List<Song> songs; private List<Song> songs;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(name = "albums_artists", @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
joinColumns = @JoinColumn(name = "album_fk"), @JoinTable(name = "artist_album",
inverseJoinColumns = @JoinColumn(name = "artist_fk")) joinColumns = {@JoinColumn(name = "album_id")},
inverseJoinColumns = {@JoinColumn(name = "artist_id")})
private List<Artist> artists; private List<Artist> artists;
public Album(){}
public Album(String albumName){ public Album() {
this.albumName = albumName; this.songs = new ArrayList<>();
}
public Long getId() {
return id;
}
public String getAlbumName(){
return albumName;
} }
public void setAlbumName(String albumName) { public Album(String name) {
this.albumName = albumName; this.albumName = name;
} this.songs = new ArrayList<>();
public List<Artist> getArtists(){
return artists;
}
public void addArtist(Artist artist){
if(artists==null)
artists=new ArrayList<>();
artists.add(artist);
artist.addAlbum(this);
}
public void setArtists(List<Artist> art){
this.artists=art;
}
public void removeArtist(Artist artist){
if(artists!=null){
artists.remove(artist);
artist.removeAlbum(this);
}
}
public List<Song> getSongs(){
return songs;
}
public void addSong(Song song){
if(songs==null)
songs = new ArrayList<>();
songs.add(song);
}
public void removeSong(Song song){
if(song!=null)
songs.remove(song);
} }
public Long getId() { return id; }
public String getAlbumName() { return albumName; }
public void setAlbumName(String name) { this.albumName = name; }
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
Album album = (Album) o; Album album = (Album) o;
if(!this.id.equals(album.getId())) return false;
if(!this.albumName.equals(album.getAlbumName())) return false;
if(artists.size() != album.getArtists().size()) return false;
if(artists.size()>0){
for (Artist art:
artists) {
boolean check = false;
for (Artist artAlb:
album.getArtists()) {
if(art.equals(artAlb))
check = true;
}
if(!check)
return false;
}
}
return Objects.equals(id, album.id); return Objects.equals(id, album.id);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id); return Objects.hash(id);
@ -97,8 +56,48 @@ public class Album {
public String toString() { public String toString() {
return "Album{" + return "Album{" +
"id=" + id + "id=" + id +
", Name='" + albumName + '\'' + ", name='" + albumName + '\'' +
"Artists:" + (artists == null ? "[]" : artists.toString()) +
'}'; '}';
} }
public void setSong(Song song){
this.songs.add(song);
if(song.getAlbum() != this){
song.setAlbum(this);
}
}
public List<Song> getSongs(){
return songs;
}
public void setSongs(List<Song> songs) {
this.songs = songs;
}
public List<Artist> getArtists(){
return artists;
}
public void setArtists(List<Artist> artists) {
this.artists = artists;
}
public void addArtist(Artist artist) {
artists.add(artist);
artist.getAlbums().add(this);
}
public List<Long> getArtistIds() {
if (artists.isEmpty()) {
return Collections.emptyList();
} else {
List<Long> artistIds = new ArrayList<>();
for (Artist artist : artists) {
if (!artistIds.contains(artist.getId())) {
artistIds.add(artist.getId());
}
}
return artistIds;
}
}
} }

View File

@ -1,66 +1,50 @@
package ru.ulstu.is.sbapp.database.model; package ru.ulstu.is.sbapp.database.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
@Table(name = "artists")
public class Artist { public class Artist {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@NotBlank
private String artistName; private String artistName;
@NotBlank
private String genre; private String genre;
@ManyToMany(fetch = FetchType.EAGER,mappedBy = "artists") @JsonBackReference
private List<Album> albums; @ManyToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER)
@JoinTable(name = "artist_album",
joinColumns = {@JoinColumn(name = "artist_id")},
inverseJoinColumns = {@JoinColumn(name = "album_id")})
private List<Album> albums = new ArrayList<>();
public Artist(){} public Artist() {
public Artist(String artistName, String genre){ }
this.artistName = artistName;
public Artist(String name, String genre) {
this.artistName = name;
this.genre = genre; this.genre = genre;
} }
public Long getId() {
return id; public Long getId() { return id; }
} public String getArtistName() { return artistName; }
public String getArtistName(){ public void setArtistName(String name) { this.artistName = name; }
return artistName; public String getGenre() { return genre; }
} public void setGenre(String genre) { this.genre = genre; }
public void setArtistName(String value){
artistName=value;
}
public String getGenre(){
return genre;
}
public void setGenre(String value){
genre=value;
}
public List<Album> getAlbums(){
return albums;
}
public void addAlbum(Album album){
if(albums==null)
albums = new ArrayList<>();
albums.add(album);
}
public void removeAlbum(Album album){
if(album!=null)
albums.remove(album);
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
Artist artist = (Artist) o; Artist artist = (Artist) o;
if(!this.artistName.equals(artist.getArtistName())) return false;
if(!this.genre.equals(artist.getGenre())) return false;
if(this.id != artist.getId()) return false;
return Objects.equals(id, artist.id); return Objects.equals(id, artist.id);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id); return Objects.hash(id);
@ -70,8 +54,29 @@ public class Artist {
public String toString() { public String toString() {
return "Artist{" + return "Artist{" +
"id=" + id + "id=" + id +
", Name='" + artistName + '\'' + ", name='" + artistName + '\'' +
", Genre='" + genre + '\'' +
'}'; '}';
} }
public List<Album> getAlbums(){
return albums;
}
public void setAlbums(List<Album> albums) {
this.albums = albums;
}
public List<Long> getAlbumIds() {
if (albums.isEmpty()) {
return Collections.emptyList();
} else {
List<Long> albumIds = new ArrayList<>();
for (Album album : albums) {
if (!albumIds.contains(album.getId())) {
albumIds.add(album.getId());
}
}
return albumIds;
}
}
} }

View File

@ -1,5 +1,6 @@
package ru.ulstu.is.sbapp.database.model; package ru.ulstu.is.sbapp.database.model;
import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*; import jakarta.persistence.*;
import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
@ -7,55 +8,41 @@ import jakarta.validation.constraints.NotNull;
import java.util.Objects; import java.util.Objects;
@Entity @Entity
@Table(name = "song") @Table(name = "songs")
public class Song { public class Song {
@Id @Id
@GeneratedValue(strategy = GenerationType.AUTO) @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; private Long id;
@NotBlank
private String songName; private String songName;
@NotBlank
private Double duration; private Double duration;
@NotNull
@ManyToOne @JsonBackReference
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "album_id", nullable = true)
private Album album; private Album album;
public Song(){}
public Song(String songName, Double duration){ public Song() {
this.songName=songName;
this.duration=duration;
}
public Long getId() {
return id;
}
public String getSongName(){
return songName;
} }
public void setSongName(String songName) { public Song(String songName, Double duration) {
this.songName = songName; this.songName = songName;
}
public Double getDuration(){return duration;}
public void setDuration(Double duration) {
this.duration = duration; this.duration = duration;
} }
public Album getAlbum() {
return album; public Long getId() { return id; }
} public String getSongName() { return songName; }
public void setAlbum(Album value){ public void setSongName(String songName) { this.songName = songName; }
album=value; public Double getDuration() { return duration;}
album.addSong(this); public void setDuration(Double duration) { this.duration = duration; }
}
@Override @Override
public boolean equals(Object o) { public boolean equals(Object o) {
if (this == o) return true; if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false; if (o == null || getClass() != o.getClass()) return false;
Song song = (Song) o; Song song = (Song) o;
if(!this.id.equals(song.getId())) return false;
if(!this.songName.equals(song.getSongName())) return false;
if(!this.duration.equals(song.getDuration())) return false;
if(!this.album.getId().equals(song.getAlbum().getId())) return false;
return Objects.equals(id, song.id); return Objects.equals(id, song.id);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id); return Objects.hash(id);
@ -63,11 +50,29 @@ public class Song {
@Override @Override
public String toString() { public String toString() {
String albumStr = (album != null) ? album.getAlbumName() : "No Album";
return "Song{" + return "Song{" +
"id=" + id + "id=" + id +
", songName='" + songName + '\'' + ", songName='" + songName + '\'' +
", Duration='" + duration + '\'' + ", duration='" + duration + '\'' +
", album='" + albumStr + '\'' +
'}'; '}';
} }
public Album getAlbum() {
return album;
}
public void setAlbum(Album album) {
if (this.album != album) {
if (this.album != null) {
this.album.getSongs().remove(this);
}
this.album = album;
if (album != null && !album.getSongs().contains(this)) {
album.getSongs().add(this);
}
}
}
} }

View File

@ -1,73 +1,60 @@
package ru.ulstu.is.sbapp.database.service; package ru.ulstu.is.sbapp.database.service;
import org.springframework.context.annotation.Lazy;
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 ru.ulstu.is.sbapp.Repository.IAlbumRepository; import ru.ulstu.is.sbapp.Repository.IAlbumRepository;
import ru.ulstu.is.sbapp.database.model.Album; import ru.ulstu.is.sbapp.database.model.Album;
import ru.ulstu.is.sbapp.database.model.Artist; import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.util.validation.ValidatorUtil; import ru.ulstu.is.sbapp.database.model.Song;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors;
@Service @Service
public class AlbumService { public class AlbumService {
private final IAlbumRepository albumRepository; private final IAlbumRepository albumRepository;
private final ValidatorUtil validatorUtil;
private final SongService songService;
private final ArtistService artistService; private final ArtistService artistService;
public AlbumService(IAlbumRepository albumRepository, ValidatorUtil validatorUtil, ArtistService artistService){ public AlbumService(IAlbumRepository albumRepository, SongService songService, @Lazy ArtistService artistService) {
this.albumRepository = albumRepository; this.albumRepository = albumRepository;
this.validatorUtil = validatorUtil; this.songService = songService;
this.artistService = artistService; this.artistService = artistService;
} }
@Transactional @Transactional
public Album addAlbum(String albumName, List<Long> artistsId) { public Album addAlbum(String name){
final Album album = new Album(albumName); if (!StringUtils.hasText(name)) {
if(artistsId.size() > 0 ) throw new IllegalArgumentException("Album name is null or empty");
{
for (Long id:
artistsId) {
Artist art = artistService.findArtist(id);
album.addArtist(art);
} }
} final Album album = new Album(name);
else
album.setArtists(new ArrayList<>());
validatorUtil.validate(album);
return albumRepository.save(album); return albumRepository.save(album);
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Album findAlbum(Long id) { public Album findAlbum(Long id){
final Optional<Album> album = albumRepository.findById(id); final Optional<Album> album = albumRepository.findById(id);
return album.orElseThrow(() -> new AlbumNotFoundException(id)); return album.orElseThrow(() -> new AlbumNotFoundException(id));
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public List<Album> findAllAlbums() { public List<Album> findAllAlbums() {
return albumRepository.findAll(); return albumRepository.findAll();
} }
@Transactional @Transactional
public Album updateAlbum(Long id, String albumName, List<Long> artistIds) { public Album updateAlbum(Long id, String name) {
if (!StringUtils.hasText(name)) {
throw new IllegalArgumentException("Album name is null or empty");
}
final Album currentAlbum = findAlbum(id); final Album currentAlbum = findAlbum(id);
currentAlbum.setAlbumName(albumName); currentAlbum.setAlbumName(name);
if(artistIds.size()>0)
{
currentAlbum.getArtists().clear();
for (Long ArtId:
artistIds) {
Artist art = artistService.findArtist(ArtId);
currentAlbum.addArtist(art);
}
}
else
currentAlbum.getArtists().clear();
validatorUtil.validate(currentAlbum);
return albumRepository.save(currentAlbum); return albumRepository.save(currentAlbum);
} }
@ -82,4 +69,72 @@ public class AlbumService {
public void deleteAllAlbums() { public void deleteAllAlbums() {
albumRepository.deleteAll(); albumRepository.deleteAll();
} }
@Transactional
public List<Song> getSongFromAlbum(Long albumId){
Optional<Album> albumOptional = albumRepository.findById(albumId);
if (albumOptional.isPresent()) {
Album album = albumOptional.get();
return album.getSongs();
} else {
throw new IllegalArgumentException("Album not found with id: " + albumId);
}
}
@Transactional
public List<Artist> getArtistInAlbum(Long albumId){
Optional<Album> albumOptional = albumRepository.findById(albumId);
if (albumOptional.isPresent()) {
Album album = albumOptional.get();
return album.getArtists();
} else {
throw new IllegalArgumentException("Album not found with id: " + albumId);
}
}
@Transactional
public List<Song> getSongsUndefined(){
List<Song> songs = new ArrayList<>();
for(Song song : songService.findAllSongs()){
if(song.getAlbum() == null){
songs.add(song);
}
}
return songs;
}
@Transactional
public void addSongToAlbum(Long albumId, List<Long> songIds){
final Album currentAlbum = findAlbum(albumId);
for(Long songId : songIds) {
songService.findSong(songId).setAlbum(currentAlbum);
}
albumRepository.save(currentAlbum);
}
@Transactional
public void deleteSongFromAlbum(Long id){
songService.findSong(id).setAlbum(null);
}
@Transactional
public void addArtistToAlbum(Long albumId, List<Long> artistIds){
final Album currentAlbum = findAlbum(albumId);
currentAlbum.setArtists(new ArrayList<>());
for(Long artistId : artistIds) {
currentAlbum.getArtists().add(artistService.findArtist(artistId));
}
albumRepository.save(currentAlbum);
}
@Transactional
public Map<String, List<String>> getAll(){
return albumRepository.getAll().stream()
.collect(
Collectors.groupingBy(
o -> (String) o[0],
Collectors.mapping( o -> (String) o[1], Collectors.toList() )
)
);
}
} }

View File

@ -2,33 +2,35 @@ package ru.ulstu.is.sbapp.database.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 ru.ulstu.is.sbapp.Repository.IArtistRepository; import ru.ulstu.is.sbapp.Repository.IArtistRepository;
import ru.ulstu.is.sbapp.database.model.Artist; import ru.ulstu.is.sbapp.database.model.Artist;
import ru.ulstu.is.sbapp.database.util.validation.ValidatorUtil;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@Service @Service
public class ArtistService { public class ArtistService {
private final IArtistRepository artistRepository; private final IArtistRepository artistRepository;
private final ValidatorUtil validatorUtil; private final AlbumService albumService;
public ArtistService(IArtistRepository artistRepository, public ArtistService(IArtistRepository artistRepository, AlbumService albumService) {
ValidatorUtil validatorUtil) {
this.artistRepository = artistRepository; this.artistRepository = artistRepository;
this.validatorUtil = validatorUtil; this.albumService = albumService;
} }
@Transactional @Transactional
public Artist addArtist(String artistName, String genre) { public Artist addArtist(String artistName, String genre){
if (!StringUtils.hasText(artistName) || !StringUtils.hasText(genre)) {
throw new IllegalArgumentException("Artist name or genre is null or empty");
}
final Artist artist = new Artist(artistName, genre); final Artist artist = new Artist(artistName, genre);
validatorUtil.validate(artist);
return artistRepository.save(artist); return artistRepository.save(artist);
} }
@Transactional(readOnly = true) @Transactional(readOnly = true)
public Artist findArtist(Long id) { public Artist findArtist(Long id){
final Optional<Artist> artist = artistRepository.findById(id); final Optional<Artist> artist = artistRepository.findById(id);
return artist.orElseThrow(() -> new ArtistNotFoundException(id)); return artist.orElseThrow(() -> new ArtistNotFoundException(id));
} }
@ -39,17 +41,19 @@ public class ArtistService {
} }
@Transactional @Transactional
public Artist updateArtist(Long id, String artistName, String genre) { public Artist updateArtist(Long id, String name, String genre) {
if (!StringUtils.hasText(name) || !StringUtils.hasText(genre)) {
throw new IllegalArgumentException("Artist name or genre is null or empty");
}
final Artist currentArtist = findArtist(id); final Artist currentArtist = findArtist(id);
currentArtist.setArtistName(artistName); currentArtist.setArtistName(name);
currentArtist.setGenre(genre);
validatorUtil.validate(currentArtist);
return artistRepository.save(currentArtist); return artistRepository.save(currentArtist);
} }
@Transactional @Transactional
public Artist deleteArtist(Long id) { public Artist deleteArtist(Long id) {
final Artist currentArtist = findArtist(id); final Artist currentArtist = findArtist(id);
currentArtist.getAlbums().clear(); // Удаляем все связи с альбомами
artistRepository.delete(currentArtist); artistRepository.delete(currentArtist);
return currentArtist; return currentArtist;
} }
@ -58,4 +62,19 @@ public class ArtistService {
public void deleteAllArtists() { public void deleteAllArtists() {
artistRepository.deleteAll(); artistRepository.deleteAll();
} }
@Transactional
public List<Object[]> getAllArtistAlbum(){
return artistRepository.getAllArtistAlbum();
}
@Transactional
public void addArtistToAlbum(Long artistId, List<Long> albumIds){
final Artist currentArtist = findArtist(artistId);
currentArtist.setAlbums(new ArrayList<>());
for(Long albumId : albumIds) {
currentArtist.getAlbums().add(albumService.findAlbum(albumId));
}
artistRepository.save(currentArtist);
}
} }

View File

@ -1,11 +1,11 @@
package ru.ulstu.is.sbapp.database.service; package ru.ulstu.is.sbapp.database.service;
import org.springframework.context.annotation.Lazy;
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 ru.ulstu.is.sbapp.Repository.ISongRepository; import ru.ulstu.is.sbapp.Repository.ISongRepository;
import ru.ulstu.is.sbapp.database.model.Album;
import ru.ulstu.is.sbapp.database.model.Song; import ru.ulstu.is.sbapp.database.model.Song;
import ru.ulstu.is.sbapp.database.util.validation.ValidatorUtil;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
@ -14,21 +14,19 @@ import java.util.Optional;
public class SongService { public class SongService {
private final ISongRepository songRepository; private final ISongRepository songRepository;
private final ValidatorUtil validatorUtil;
private final AlbumService albumService; private final AlbumService albumService;
public SongService(ISongRepository songRepository, ValidatorUtil validatorUtil, AlbumService albumService){ public SongService(ISongRepository songRepository, @Lazy AlbumService albumService) {
this.songRepository = songRepository; this.songRepository = songRepository;
this.validatorUtil = validatorUtil;
this.albumService = albumService; this.albumService = albumService;
} }
@Transactional @Transactional
public Song addSong(String songName, Double duration, Long albumId){ public Song addSong(String songName, Double duration){
final Song song = new Song(songName,duration); if (!StringUtils.hasText(songName) || !StringUtils.hasText(String.valueOf(duration))) {
Album curAlbum = albumService.findAlbum(albumId); throw new IllegalArgumentException("Song name or duration is null or empty");
song.setAlbum(curAlbum); }
validatorUtil.validate(song); final Song song = new Song(songName, duration);
return songRepository.save(song); return songRepository.save(song);
} }
@ -44,13 +42,13 @@ public class SongService {
} }
@Transactional @Transactional
public Song updateSong(Long id, String songName, Double duration, Long albumId) { public Song updateSong(Long id, String name, Double duration) {
if (!StringUtils.hasText(name) || !StringUtils.hasText(String.valueOf(duration))) {
throw new IllegalArgumentException("Song name or duration is null or empty");
}
final Song currentSong = findSong(id); final Song currentSong = findSong(id);
currentSong.setSongName(songName); currentSong.setSongName(name);
currentSong.setDuration(duration); currentSong.setDuration(duration);
Album curAlbum = albumService.findAlbum(albumId);
currentSong.setAlbum(curAlbum);
validatorUtil.validate(currentSong);
return songRepository.save(currentSong); return songRepository.save(currentSong);
} }
@ -62,7 +60,18 @@ public class SongService {
} }
@Transactional @Transactional
public void deleteAllSongs() { public void deleteAllSong() {
songRepository.deleteAll(); songRepository.deleteAll();
} }
// @Transactional
// public void AddSongToAlbum(Long idSong, Long idAlbum){
// Song song = findSong(idSong);
// Album album = em.find(Album.class, idAlbum);
// if (album == null || song == null) {
// throw new EntityNotFoundException("Album or Song not found");
// }
// song.setAlbum(album);
// em.merge(song);
// }
} }