0

I have a Spring Boot app that uses H2 database locally and everything works fine. Now I uploaded the app to Heroku. In Heroku I have a Heroku Postgres add-on. The app has many entities and everything else is working, but the entity with a byte[] property does not work. This I concluded from the fact that dynamically added images that should be found in the database, are not found.

The Entity that causes problems:

package projekti;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.JoinColumn;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.jpa.domain.AbstractPersistable;

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
public class Photo extends AbstractPersistable<Long> {

    @Lob
    @Basic(fetch = FetchType.LAZY)
    private byte[] content;
    
    @ManyToOne
    @JoinColumn(name = "author_id")
    private Saunoja author;

    private String description;

    private Boolean isProfilePicture;

    private ArrayList<String> likes;

    @OneToMany(cascade = CascadeType.ALL, targetEntity = Comment.class, mappedBy = "photo")
    private List<Comment> comments;

    private LocalDateTime created;

}

The byte[] is made into a image with the following Controller method:

@GetMapping("/photo/{id}")
    public void showPhoto(@PathVariable Long id, HttpServletResponse response) throws IOException {

        response.setContentType("image/jpg");

        Photo photo = photoRepository.getOne(id);

        InputStream is = new ByteArrayInputStream(photo.getContent());

        IOUtils.copy(is, response.getOutputStream());
    }

I am very new to Heroku and postgres, so I have not come up with a way to explore the database the way I can with H2-console locally, but I found out that the number of tables in Heroku-Postgres is correct. Meaning that there is a table for "Photo".

mortar-1
  • 97
  • 7
  • Have you checked the postgress db encoding is correct? I believe its better to store image in base64 format – ray Aug 23 '21 at 20:55
  • Hi, thanks for the answer. I got the problem fixed at the Heroku PostgreSQL end with adding the following annotation to the byte[] variable: @Type(type = "org.hibernate.type.BinaryType"). BUT, now when running locally (H2, Hibernate), i get the following error: Value too long for column "CONTENT VARBINARY(255)". Content is the name of the variable. – mortar-1 Aug 24 '21 at 07:11
  • 1
    Solution found from Peter Butkovics answer to this question: https://stackoverflow.com/questions/3677380/proper-hibernate-annotation-for-byte – mortar-1 Aug 24 '21 at 10:26

0 Answers0