-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathDatabaseInitializer.java
More file actions
67 lines (57 loc) · 2.03 KB
/
DatabaseInitializer.java
File metadata and controls
67 lines (57 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package org.example;
import org.example.entity.Album;
import org.example.entity.Artist;
import org.example.entity.Song;
import org.example.repo.AlbumRepository;
import org.example.repo.ArtistRepository;
import org.example.repo.SongRepository;
import java.util.List;
public class DatabaseInitializer {
private final ItunesApiClient apiClient;
private final SongRepository songRepo;
private final AlbumRepository albumRepo;
private final ArtistRepository artistRepo;
public DatabaseInitializer(ItunesApiClient apiClient, SongRepository songRepo , AlbumRepository albumRepo, ArtistRepository artistRepo) {
this.apiClient = apiClient;
this.songRepo = songRepo;
this.albumRepo = albumRepo;
this.artistRepo = artistRepo;
}
public void init() {
if (songRepo.count() > 0) { //check if there is data already
return;
}
List<String> searches = List.of("the+war+on+drugs",
"refused",
"thrice",
"16+horsepower",
"viagra+boys",
"geese",
"ghost",
"run+the+jewels",
"rammstein",
"salvatore+ganacci",
"baroness"
);
for (String term : searches) {
try {
apiClient.searchSongs(term).forEach(dto -> {
Artist ar = Artist.fromDTO(dto);
if (!artistRepo.existsByUniqueId(ar)) {
artistRepo.save(ar);
}
Album al = Album.fromDTO(dto, ar);
if (!albumRepo.existsByUniqueId(al)) {
albumRepo.save(al);
}
Song s = Song.fromDTO(dto, al);
if (!songRepo.existsByUniqueId(s)) {
songRepo.save(s);
}
});
} catch (Exception e) {
throw new RuntimeException("Failed to fetch or persist data for search term: " + term, e);
}
}
}
}