Home » Java » postgresql – Storing a java.sql.Blob with Hibernate in Postgres DB produces multiple entries in pg_largeobject_metadata-Exceptionshub

postgresql – Storing a java.sql.Blob with Hibernate in Postgres DB produces multiple entries in pg_largeobject_metadata-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have an application using hibernate 5.4.10 and Postgres 11 database.
When I store the Entity “FileObject” which contains a BLOB, Postgres adds an entry to table pg_largeobject_metadata. This is expected and correct.
But when I store the same object a second time to update the fileName, another entry in pg_largeobject_metadata appears.

    select count(*) from pg_largeobject_metadata

returns 2 but should be 1

Here is the Entity..

@Entity
@Data
@EqualsAndHashCode(of = "id")
public class FileObject {

    @Id
    @GeneratedValue
    private Long id;

    @NotNull
    private String fileName;

    @NotNull
    private Long length;

    @Lob
    private Blob data;

}

Every further save() produces one more entry. This is wrong.

    Optional <FileObject> fileObject = fileRepository.findById( (long) 1 );
    if (!fileObject.isEmpty()) {
        FileObject file2 = fileRepository.save(fileObject.get()); // saving produces on more entry in pg_largeobject_metadata
        fileRepository.save(file2); // again on more entry .. 

    }

How can I change this behaviour?
If possible, it should be a solution which is working for other databases too.

How to&Answers: