'Spring boot - NonUniqueResultException: query did not return a unique result: error

I have 1 entities, Post and FileUploads where a post can have many FileUploads (to add images to the post/advert)

I am able to send a request for the first time and the data is persisted properly in the database, the issue is when I try to create another Post with the FileUploads that I get this error.

I'm not sure what's causing it. Only the first post with the FileUploads gets persisted, after that only the posts get persisted without the FileUploads.

Post.java

@Entity
public class Post {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotBlank(message = "Required")
    @Size(max=45, message = "Maximum of 45 letters")
    @Column()
    private String title;

    @NotBlank(message = "Required")
    @Size(min = 40, message = "Minimum of 40 characters")
    @Column()
    private String description;

    @NotBlank(message = "Required")
    @Column()
    private String brand;

    @NotBlank(message = "Required")
    @Column()
    private String model;

    @NotNull(message = "Required")
    @Column()
    private Double price;

    @NotBlank(message = "Required")
    @Column()
    private String color;

    @NotNull(message = "Required")
    @Column()
    private Double kilometers;

    @NotBlank(message = "Required")
    @Column()
    private String bodyType;

    @NotBlank(message = "Required")
    @Column()
    private String fuelType;

    @NotBlank(message = "Required")
    @Column()
    private String transmission;

    @NotNull(message = "Required")
    @Column()
    private Integer year;

    @NotBlank(message = "Required")
    @Column()
    private String location;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "post")
    private List<FileUpload> fileUploads = new ArrayList<>();

    @Column(name="post_creator_email")
    private String postCreatorEmail;

    @Column(name="post_creator_name")
    private String postCreatorName;

    public Post() {
    }

// getters and setters


FileUpload.java

@Entity
public class FileUpload {

    @Id
    @GenericGenerator(name = "uuid", strategy = "uuid2")
    @GeneratedValue(generator = "uuid")
    private String fileId;

    @Column(name="name")
    private String name;

    @Column(name="type")
    private String type;

    @Column(name="file_uploader")
    private String fileUploader;

    @Column(name="image_count")
    private int imageCount;

    @Lob
    @JsonIgnore
    @Column(name="data")
    private byte[] data;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="post_id")
    @JsonIgnore
    private Post post;

    public FileUpload() {

    }

    public FileUpload(String name, String type, String fileUploader, int imageCount, byte[] data) {
        this.name = name;
        this.type = type;
        this.fileUploader = fileUploader;
        this.imageCount = imageCount;
        this.data = data;
    }
}


FileUploadServiceImpl.java (method to store images)

    @Override
    public void uploadPostImages(List<FileUpload> fileUploadList, String emailAddress) {
        Post thePost = postRepository.findPostByPostCreatorEmail(emailAddress);

        if(thePost == null) {
            System.out.println("post is null");
            throw new PostNotFoundException("No post found for email " + emailAddress);
        }


        for(FileUpload fileUpload : fileUploadList) {
            fileUpload.setPost(thePost);
        }
        thePost.setFileUploads(fileUploadList);
        postRepository.save(thePost);

    }

PostServiceImpl.java (method to create post)

 @Override
    public void createOrUpdatePost(String post, String emailAddress) {
        Post thePost = new Post();

        if (thePost.getId() != null) { //checks if a post with ID already exists
            thePost = postRepository.findPostById(thePost.getId());

            if (thePost != null && !(thePost.getPostCreatorEmail().equals(emailAddress))) {
                throw new PostNotFoundException("Post not found in your account");
            } else if (thePost == null) {
                throw new PostNotFoundException("Post does not exist");
            }
        }

        // if a post does not exist, CREATE
        try {
            User user = userRepository.findUserByEmailAddress(emailAddress);
            System.out.println("looking for user with email: " + emailAddress);

            ObjectMapper objectMapper = new ObjectMapper();
            thePost = objectMapper.readValue(post, Post.class);

            user.setTotalAds(++count);
            thePost.setPostCreatorName(user.getFullName());
            thePost.setPostCreatorEmail(emailAddress);
            thePost.setUser(user);
            userRepository.save(user);
            postRepository.save(thePost);
        } catch (Exception e) {
            throw new PostAlreadyExistsException("Post with title " + thePost.getTitle() + " already exists");
        }

    }

PostController.java


    @PostMapping("/create")
    public ResponseEntity<?> createPost(@RequestPart("files") MultipartFile[] files, @Valid @RequestPart String post,  BindingResult result, Principal principal) throws IOException {
        ResponseEntity<?> errorMap = errorValidationService.validationService(result);
        if(errorMap != null) return errorMap;

        String message = "";

        try {
            List<FileUpload> fileList = new ArrayList<>();

            for (MultipartFile file : files) {
                String fileContentType = file.getContentType();
                String fileName = file.getOriginalFilename();
                FileUpload fileUpload = new FileUpload(fileName, fileContentType, principal.getName(),++imageCount, file.getBytes());

                fileList.add(fileUpload);
            }

            postService.createOrUpdatePost(post, principal.getName());
            fileUploadService.uploadPostImages(fileList, principal.getName());

            message = "Uploaded the files successfully";
            return ResponseEntity.status(HttpStatus.OK).body(new ApiResponse(message, true));
        } catch(Exception e) {
            message = e.getMessage();
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ApiResponse(message, false));
        }

I am making sure to change all the fields on the second request but i'm still having the same error message no matter what..



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source