我使用的是springboot和mysql。我尝试在播放列表表中添加新实体(歌曲)。他们有多对多的关系。但正如您在mysql查询后的回答中看到的,它并没有保存。其他关系正常
播放列表实体
@Data
@Entity
@Component
@Getter
@EqualsAndHashCode(exclude = "songs")
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "playlists")
public class PlaylistEntity {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
private String playlistTitle;
@ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.MERGE})
@JoinColumn(name = "user_id", nullable = false)
private UserEntity user;
private LocalDateTime createdAt;
public PlaylistEntity(String playlistTitle, UserEntity user, LocalDateTime createdAt) {
this.playlistTitle = playlistTitle;
this.user = user;
this.createdAt = createdAt;
}
@Transient
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(name = "playlist_song",
joinColumns = @JoinColumn(name = "playlist_id", nullable=false),
inverseJoinColumns = @JoinColumn(name = "song_id", nullable=false))
private Set<SongEntity> songs = new HashSet<>();
}
播放列表存储库
@Repository
public interface PlaylistRepository extends PagingAndSortingRepository<PlaylistEntity, String> {
@Query(value = "select * from playlists where user_id = :id", nativeQuery = true)
List<PlaylistEntity> showAllUserPlaylists(@Param("id") String id);
@Query(value = "select * from playlists where playlist_title = :playlist_title", nativeQuery = true)
PlaylistEntity findByName(@Param("playlist_title") String playlist_title);
}
宋体
@Data
@Entity
@Builder
@Getter
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "songs")
public class SongEntity {
@Id
@GeneratedValue(generator = "uuid")
@GenericGenerator(name = "uuid", strategy = "uuid2")
private String id;
private String title;
private String artist;
private String album;
private String genre;
@CreationTimestamp
private LocalDateTime releaseDate;
private int likes;
@Transient
@EqualsAndHashCode.Exclude
@ManyToMany(mappedBy = "songs")
private Set<PlaylistEntity> playlistEntities = new HashSet<>();
@Transient
@ManyToMany(mappedBy = "songs")
@EqualsAndHashCode.Exclude
private Set<SubscriptionEntity> subscriptionEntities = new HashSet<>();
public SongEntity(String name) {
this.title = name;
}
}
歌曲库
@Repository
public interface SongRepository extends JpaRepository<SongEntity, String> {
@Query(value="SELECT * FROM songs WHERE (:genre is null or genre = :genre) " +
"AND (:artist IS NULL or artist = :artist)", nativeQuery=true)
List<SongEntity> findByParams(@Param("genre") String genre, @Param("artist") String artist);
@Query(value="SELECT * FROM songs WHERE artist = :artist", nativeQuery=true)
List<SongEntity> findByArtist(@Param("artist") String artist);
@Query(value="SELECT * FROM songs WHERE genre = :genre", nativeQuery=true)
List<SongEntity> findByGenre(@Param("genre") String genre);
@Query(value = "SELECT s.title, s.likes FROM SongEntity s WHERE s.artist = :artist")
List<SongEntity> showSongsStatistics(@Param("artist") String artist);
}
在播放列表表中保存歌曲的方法
@Transactional
public Playlist addSongToPlaylist(String playlistId, String songId) throws Exception {
SongEntity addedSong = findSongById(songId)
PlaylistEntity requiredPlaylist = findPlaylistById(playlistId);
requiredPlaylist.getSongs().add(addedSong);
PlaylistEntity updatedPlaylist = playlistRepository.save(requiredPlaylist);
return playlistConverter.fromEntity(updatedPlaylist);
}
和控制器
@Slf4j
@Configuration
@RestController
@AllArgsConstructor
@RequestMapping("/user/playlists")
public class PlaylistController {
private final PlaylistService playlistService;
@PostMapping(value = ADD_SONG_TO_PLAYLIST_URL)
Playlist addSongToThePlaylist(@RequestParam String playlistId, @RequestParam String songId) throws Exception {
return playlistService.addSongToPlaylist(playlistId, songId);
}
@UtilityClass
public static class Links {
public static final String ADD_SONG_TO_PLAYLIST_URL = "/addSong";
}
}
我用 Postman 提出请求。在请求之后,我得到了这个答案,这表明这首歌被添加到了播放列表中。https://i.stack.imgur.com/vdfbc.png
但正如我所说,如果检查播放列表的歌曲数据库,它什么都没有。这意味着我的程序不能正确地保存多对多表。https://i.stack.imgur.com/9lgw9.png
日志中也有例外。
所以我能理解什么是错的。希望有人有主意。
1条答案
按热度按时间2ekbmq321#
对于songentity
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
,您没有任何显式包含的注解。您列出了一些要排除的,但基于https://projectlombok.org/features/equalsandhashcode,似乎需要在使用此标志时显式地将它们标记为包含。我不是100%确定当你把这个标志放在类级别,但是没有显式包含任何东西时,lombok会做什么,但是它看起来像是一个无效的状态,可能会弄乱你的equals和hashcode,从而弄乱跟踪hashset bucket中表示你正在添加的歌曲的项的能力。
所以我首先要解决这个问题,使equals/hashcode是正确的。看起来你要么
onlyExplicitlyIncluded=true
设置或您实际添加特定的包含。下面是一个线程,它讨论了如果您想坚持使用显式includes的话:如何将@equalsandhashcode与include-lombok一起使用
还有,为什么你们的关系上有@transient注解?该注解通常告诉entitymanager忽略它附加到的内容。在您的例子中,如果您正在向集合中添加一些内容,但是将集合标记为@transient,那么直观地说,它不应该影响数据库中的数据。建议删除那些希望关系/集合中对象的更改实际反映在数据库中的注解。