I have a class that has Users @entity. Which has a profile picture that needs to update, When I pass the @Query the image name update and I can see the image in the folder too. But in my API, I have a imageName return so I can do assynchronize change. The weired part is when I upload the image, image get uploaded in a folder and in the database too, but throw 500 error. Never saw this happen Before. Any help will be appreciated.
POJO Class
@Entity
@Table(name="users")
public class Users {
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(name = "firstname")
private String firstName;
@Column(name = "lastname")
private String lastName;
@Id
@Column(name = "username")
private String username;
@Column(name = "email")
private String email;
@Column(name = "role")
private String role;
@Column(name = "profile_picture")
private String profilePicture;
}
Profile Picture Class
public class ProfilePicture {
private MultipartFile profileImage;
private String profileImageName;
}
Repository
public interface ProfileRepository extends JpaRepository<Users, String> {
@Query(value = "UPDATE users SET profile_picture = :saveImage WHERE username = :username", nativeQuery = true)
public String updateUserProfilePictureForUsername(@Param("saveImage") String saveImage, @Param("username") String username);
}
Service:
public void saveProfileImage(ProfilePicture saveImage, String username) {
String imageName = saveImage.getProfileImageName();
profileRepo.updateUserProfilePictureForUsername(imageName, username);
}
REST API
@PostMapping(path = "/uploadprofileimage")
@ResponseStatus(HttpStatus.CREATED)
public String uploadProfilePicture(@RequestParam("image") MultipartFile Imagefile, @RequestParam("username") String username) throws IOException {
String profileImageName = Imagefile.getOriginalFilename();
ProfilePicture profileImage = new ProfilePicture();
String fileFolderPath = "/Users/Desktop/Documents/" + username + /ProfilePictures/";
File filePath = new File(fileFolderPath);
if (!filePath.exists()) {
filePath.mkdirs();
}
File file = new File(fileFolderPath, profileImageName);
profileImage.setProfileImageName(profileImageName);
profileImage.setProfileImage(Imagefile);
profileImage.getProfileImage().transferTo(file);
profileService.saveProfileImage(profileImage, username);
return profileImage.getProfileImageName();
}
This is the Solution using Lambda Expression.
public Users saveProfileImage(ProfilePicture saveImage, String username) {
String imageName = saveImage.getProfileImageName();
return profileRepo.findById(username).map( user -> {
user.setProfilePicture(imageName);
return profileRepo.save(user);
}).orElseThrow(() -> new ResourceNotFoundException("Something went wrong "));
}