0

I have spring-boot-starter-parent v3.1.2 with hibernate v6.2.6. I am trying to save byte[] to postgresql and get the next error

column "data" is of type bytea but expression is of type bigint
Hint: You will need to rewrite or cast the expression.

I have found some solution for hibernate v5 like this @Type(type = "org.hibernate.type.ImageType") and @Type(type = "org.hibernate.type.BinaryType") but nothing for v6

Any ideas?

@Entity
@Getter
@Setter
@Table(name = "image")
@ToString(exclude = {"data"})
public class ImageEntity {

    @Id
    private UUID id;

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

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

    @Lob
    private byte [] data;
}

@SpringBootApplication
@EnableJpaRepositories(basePackages = "com.example.image")
public class DemoApplication implements ApplicationRunner {

    @Autowired
    private ImageRepository imageRepository;

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {
        ImageEntity imageEntity = new ImageEntity();
        imageEntity.setId(UUID.randomUUID());
        imageEntity.setFileName("image.jpg");
        imageEntity.setContentType("image/jpeg");
        imageEntity.setData(Files.readAllBytes(Paths.get("image.jpg")));

        imageRepository.save(imageEntity);
    }
}
CREATE TABLE public.image (
    id uuid NOT NULL,
    file_name varchar(255) NULL,
    content_type varchar(255) NULL,
    "data" bytea NULL,
    CONSTRAINT image_pk PRIMARY KEY (id)
);

1 Answers1

0

in case you not found the answer already on stackoverflow. This explains it well: Unable to use Spring Data JPA to extract users that have a byte[] of a profile Image

In short: you use postgres type bytea, Hibernate (6.2) uses @Lob annotation to try and use postgres OID mechanism. If you remove @Lob it uses the correct mapping. I think you also have to add:

@Column(name = "data", columnDefinition="bytea")

to your data field.

Kind regards, Knut

Knut
  • 136
  • 2
  • 11