How to save a big file to and read it from database with hibernate with low-memory usage?
Question
I want to save some file content to database with hibernate, my model for hibernate is:
import javax.persistence.*;
import java.io.Serializable;
import static javax.persistence.AccessType.FIELD;
@Entity
@Access(FIELD)
@Table(name = "MYFILE")
public class MyFile implements Serializable {
@Id
@SequenceGenerator(name = "MYSEQ", sequenceName = "MYSEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MYSEQ")
@Column(name = "ID")
private Long id;
@Column(name = "FILE_CONTENT")
@Lob
private byte[] fileContent;
// getters and setters
}
You can see the type of the fileContent
field is byte[]
, and there is a @Lob
on it.
It's working well, but the problem is if the files are huge, e.g. 10M, or 20M, it will use a lot of memory, which is an issue in production.
I wonder if there is any way to make it using low memory, say, use a stream
instead of byte[]
? But I'm not sure what is the correct solution.
No correct solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow