Search code examples
javaspring-bootfileh2file-storage

How to store files in H2 database - Spring Boot


Question

How do I store entire files in my H2 database and retrieve them using JDBC?


Some Background

I have some text files that I have as templates for various documents that will be generated in my Spring Boot app. Currently, I have my text files stored in my local file system on my PC, but that is not a long term solution. I need to somehow store them in the database and provide the necessary code for the JDBC for the retrieval of the files.

Are there any technologies/libraries out there that would help me with this? If so, please link me to them and provide an example of how to do it in Spring Boot.


Note: It is a new requirement given to me that the text files should be stored in the database, and not the file system.


Solution

  • You have to use a BLOB column in your database table.

    CREATE TABLE my_table(ID INT PRIMARY KEY, document BLOB);
    

    BLOB stands for Binary Large Object. http://www.h2database.com/html/datatypes.html#blob_type

    To store it with JdbcTemplate you have to create a ByteArrayInputStream

    ByteArrayInputStream inputStream = new ByteArrayInputStream(document);
    preparedStatement.setBlob(3, inputStream);
    

    Please find more examples here: https://www.logicbig.com/tutorials/spring-framework/spring-data-access-with-jdbc/jdbc-template-with-clob-blob.html