Search code examples
javaspringspring-bootspring-data-jpamultiple-file-upload

Posting multiple files to Database - Null value for ManyToOne relationship


I have two entities with onetomany and manytoone relation like below:

@Entity
@Table(name="file_model")
public class FileModel {
....
@JoinColumn(name = "userid", referencedColumnName = "id")
@ManyToOne(optional = false)
private AppUser appUser;
....
}


@Entity
@Table(name="app_user")
public class FileModel {
....
@OneToMany(cascade = CascadeType.ALL, mappedBy = "appUser")
private Set<FileModel> appUserFiles;
....
}

I am trying to post Multiple files using SpringBoot Data/JPA to Database. I have following in my controller. At the same time I am trying to set userid for each file that will be saved.

@RequestMapping(value = { "/addDocument/{id}" }, method = RequestMethod.POST)
    public String uploadDocument(@RequestParam("files") MultipartFile[] files, @PathVariable Long id, ModelMap model)
            throws IOException {
        List<String> fileNames = new ArrayList<String>();
        AppUser appUser = appUserRepository.findById(id).get();
        System.out.println("User ID is :: " + appUser.getId());
        System.out.println("User EMail is :: " + appUser.getUseremail());
        try {
            List<FileModel> storedFile = new ArrayList<FileModel>();
            for (MultipartFile file : files) {
                FileModel fileModel = new FileModel();
                fileModel.setAppUser(appUser);
                fileModel = new FileModel(file.getOriginalFilename(), file.getContentType(), file.getBytes());
                fileNames.add(file.getOriginalFilename());
                storedFile.add(fileModel);
            }
            fileRepository.saveAll(storedFile);
            model.addAttribute("message", "All files uploaded successfully!");
            model.addAttribute("files", fileNames);
        } catch (Exception e) {
            model.addAttribute("message", "ERROR. File Upload Failed !!");
            model.addAttribute("files", fileNames);
            e.printStackTrace();
        }

        return "redirect:/addDocument/" + id;
    }

And this what I get at the console:

User ID is :: 1
User EMail is :: user1@mydomain.com
2020-07-19 16:37:43.951  WARN 39179 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 23502, SQLState: 23502
2020-07-19 16:37:43.952 ERROR 39179 --- [nio-8080-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper   : NULL not allowed for column "USERID"; SQL statement:
insert into file_model (created_at, updated_at, userid, mimetype, name, pic, id) values (?, ?, ?, ?, ?, ?, ?) [23502-200]
org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement

Now, since my AppUser object is created successfully (as seen from the sysout values of id and email-id) why I am getting this exception? What I am missing here?


Solution

  • you did write the following code:

    for (MultipartFile file : files) {
                FileModel fileModel = new FileModel();
                fileModel.setAppUser(appUser);
                fileModel = new FileModel(file.getOriginalFilename(), file.getContentType(), file.getBytes());
                fileNames.add(file.getOriginalFilename());
                storedFile.add(fileModel);
            }
    

    But the problem is that first you are setting fileModel to new FileModel() and two lines later, you are doing that again, so that the line fileModel.setAppUser(appUser) is senseless. Just leave it like this and it should work:

    final FileModel fileModel = new FileModel(file.getOriginalFilename(), file.getContentType(), file.getBytes());
    fileModel.setAppUser(appUser);
    fileNames.add(file.getOriginalFilename());
    storedFile.add(fileModel);
    

    Also try to use "final" as much as possible. Especially in this case, if you would have used "final", you would have realized that you are overriding your object.

    Best regards