[英]Delete object from an entity with a OneToMany relationship between both using JPA in Spring Boot
下午好,我正在使用 REST API,其中我有一個包含許多歌曲的播放列表,為此我使用 JPA 和允許我在兩者之間建立關系的好處。 現在,如果我想刪除已經添加到播放列表中的歌曲,我做不到,我在下面向您展示我的課程
Class 播放列表
@Entity
@Table(name = "PLAY_LIST")
public class PlayList {
@JsonIgnore
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
//@JsonView(View.Get.class)
@Column(name="name")
private String name;
//@JsonView(View.Get.class)
@Column(name="description")
private String description;
//@JsonView(View.Get.class)
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true, mappedBy = "playList")
private List<Song> songs = new ArrayList<>();
@Transient
public void addSong(Song song) {
song.setPlayList(this);
songs.add(song);
}
@Transient
public void removeSong(Song song) {
songs.remove(song);
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Song> getSongs() {
return this.songs;
}
public void setSongs(List<Song> songs) {
this.songs = songs;
}
}
在這里,我有添加歌曲和刪除的方法,但是,刪除對我不起作用。
Class 宋
Entity
@Table(name = "SONG")
public class Song{
@JsonIgnore
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;
//@JsonView(View.Create.class)
@Column(name = "title")
private String title;
//@JsonView(View.Create.class)
@Column(name = "artist")
private String artist;
//@JsonView(View.Create.class)
@Column(name = "album")
private String album;
//@JsonView(View.Create.class)
@Column(name = "year")
private int year;
/*
Fetch: Esta propiedad se utiliza para determinar cómo debe ser cargada la entidad.
LAZY (perezoso): Indica que la relación solo se cargará cuando la propiedad sea leída por primera vez */
//@JsonView(View.Get.class)
@JsonIgnore
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "PLAY_LIST_ID")
private PlayList playList;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
public String getArtist() {
return this.artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getAlbum() {
return this.album;
}
public void setAlbum(String album) {
this.album = album;
}
public int getYear() {
return this.year;
}
public void setYear(int year) {
this.year = year;
}
public PlayList getPlayList() {
return this.playList;
}
public void setPlayList(PlayList playList) {
this.playList = playList;
}
}
我的 class Controller
@RestController
@RequestMapping("playlist")
public class PlayListController {
@Autowired
private PlayListService playListService;
@Autowired
private SongRepository songRepository;
// Get playlist by id with songs belongs that playlist
@GetMapping("/get/{id}")
public Optional<PlayList> getPlayListByID(@PathVariable(value = "id") Long id) {
Optional<PlayList> playList = playListService.getById(id);
return playList;
}
@PostMapping("/create")
public PlayList createPlayList(@RequestBody PlayListDTO playListDTO) {
PlayList playList = new PlayList();
playList.setName(playListDTO.getName());
playList.setDescription(playListDTO.getDescription());
playList.setSongs(new ArrayList<>());
for (int x=0; x<playListDTO.getSongs().size(); x++) {
Song songs=new Song();
songs.setTitle(playListDTO.getSongs().get(x).getTitle());
songs.setArtist(playListDTO.getSongs().get(x).getArtist());
songs.setAlbum(playListDTO.getSongs().get(x).getAlbum());
songs.setYear(playListDTO.getSongs().get(x).getYear());
playList.addSong(songs);
}
return playListService.savePlayList(playList);
}
@PutMapping("/update/{id}")
public PlayList updatePlayList(@PathVariable(value = "id") Long id,@RequestBody Song song){
PlayList playList = playListService.getById(id).get();
song.setPlayList(playList);
playList.getSongs().add(song);
playListService.savePlayList(playList);
return playList;
}
@DeleteMapping("/delete/{id}")
public PlayList deletePlayList(@PathVariable(value = "id") Long id,@RequestBody Song song){
PlayList playList =playListService.getById(id).get();
System.out.println(playList.getSongs());
playList.removeSong(song);
System.out.println(playList.getSongs());
return playList;
}
}
所以我用它的歌曲存儲播放列表,方法 POST
{
"name": "Lista 1",
"description": "Lista de reproduccion 2020 spotify",
"songs": [
{
"title": "Tan Enamorados",
"artist": "CNCO",
"album": "Tan Enamorados",
"year": 2020
},
{
"title": "Hawai",
"artist": "Maluma",
"album": "PAPI JUANCHO",
"year": 2020
}
]
}
現在,為了消除我正在傳遞播放列表的 id 和歌曲的請求(沒有在 BD 中自動創建的歌曲的 id 的對象),但是,我無法從播放列表中消除歌曲,並且在日志級別它返回這個在控制台中打印
例如,我想刪除以下歌曲:
但是它沒有被刪除,它返回相同的列表給我
我是否錯過了無需刪除播放列表即可刪除歌曲的內容?
使用PlayList
中的所有歌曲列表刪除一首歌曲並不是一個好主意。 @OneToMany
關聯沒有連接表。 所以我們可以更簡單地刪除一首歌曲,使用SONG
表(這是@OneToMany
的連接表不方便的主要原因)。
為此,您需要一個歌曲 ID,並且需要使用CrudRepository.deleteById()
方法。 您可以為此使用完整組合(標題、藝術家、專輯、年份),但將歌曲 ID 添加到 JSON 會更簡單。
最好用這個端點URL來刪除一首歌
/{playListId}/songs/{songId}
您不需要delete
URL 中的部分,您已經使用了 DELETE HTTP 方法。
為什么你的代碼不起作用
@Transient
public void removeSong(Song song) {
songs.remove(song);
}
songs.remove()
無法在列表中找到song
,List.remove( List.remove()
通過引用找到歌曲。 它需要有一個開放的持久上下文並從中獲取一首歌曲才能在列表中找到它。
所以一個有效的場景
start @Transactional
Spring starts a database transaction
Spring opens a persistent context
load PlayList
load a song from the database (using id or other song attributes)
delete a song from PlayList songs (or delete a song from PlayList songs using id)
end @Transactional
Hibernate flushes changes and delete a song in the database
persistent context is closed
database transaction is committed
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.