JpaRepository и контроллер
Возник такой вопрос: У меня есть контроллер и в нём реализованы 2 метода - загрузка(addSong) и скачивание(getSong) файлов. С загрузкой файлов на сервер всё нормально, проблема в скачивание. При попытки найти в БД запись по id(integer) я получаю Entity с пустыми свойствами и по итогу не могу скачать файл. Я пытался исправить это, но не получалось. По итогу в методе addSong я добавил строчку кода, которая читает все записи таблицы в БД(readAll) и больше ничего не изменял. После этого по id я получаю нужную мне Entity со всеми его значениями. Чем может быть обусловлено такое поведение?
Код контроллера:
@Controller
public class SongController {
private final SongDataServices context;
public SongController(SongDataServices context) {
this.context = context;
}
@GetMapping("/home")
public String homePage(){
return "home";
}
@Value("${upload.path}")
private String uploadPath;
@GetMapping("/getSong/{id}")
public void getSong(@PathVariable int id, HttpServletResponse response){
var t = context.readAll();
Song song = null;
song = context.read(id);
if (song == null)
return;
else {
String fileName = song.getUrl();
Path file = Paths.get(fileName);
if (Files.exists(file)){
response.setHeader("Content-disposition", "attachment;filename=" + fileName);
response.setContentType("application/octet-stream");
try {
Files.copy(file, response.getOutputStream());
response.getOutputStream().flush();
} catch (IOException e) {
//LOG.info("Error writing file to output stream. Filename was '{}'" + fileName, e);
throw new RuntimeException("IOError writing file to output stream");
}
}
}
}
@PostMapping("/addSong")
public String addSong(@RequestParam("file") MultipartFile file) throws IOException {
if (file !=null){
File uploadDir = new File(uploadPath);
if(!uploadDir.exists()){
uploadDir.mkdir();
}
String uuidFile = UUID.randomUUID().toString();
String resultFileName = uuidFile + "." + file.getOriginalFilename();
String absoluteFileName = uploadPath + "/" + resultFileName;
file.transferTo(new File(absoluteFileName));
var temp =new Song();
temp.setTitle(resultFileName);
temp.setUrl(absoluteFileName);
context.create(temp);
}
return "Answer";
}
}
Код SongDataServices:
@Service
public class SongDataServices implements IDataService<Song> {
protected final SongRepository repository;
@Autowired
public SongDataServices(SongRepository repository) {
this.repository = repository;
}
@Override
public void create(Song song) {
repository.save(song);
}
@Override
public List<Song> readAll() {
return repository.findAll();
}
@Override
public Song read(int id) {
return repository.getOne(id);
}
@Override
public boolean update(Song client, int id) {
if (repository.existsById(id)) {
client.setId(id);
repository.save(client);
return true;
}
return false;
}
@Override
public boolean delete(int id) {
if (repository.existsById(id)) {
repository.deleteById(id);
return true;
}
return false;
}
}
Код SongRepository:
@Repository
public interface SongRepository extends JpaRepository<Song, Integer> {
}
Код MvcConfig:
@Configuration
public class MvcConfig implements WebMvcConfigurer {
@Value("${upload.path}")
private String uploadPath;
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/mp3/**")
.addResourceLocations("file://" + uploadPath + "/");
}
}
Код Entity:
@Entity
@Table(name = "songs")
public class Song {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
private String title;
private String author;
private int year;
private String duration;
@Column(name = "user_id")
public int userId;
public String url;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}