You should take a look at the community project Spring Content. This project gives you a Spring Data-like approach to content. It is to unstructured data (documents, images, videos, etc), what Spring Data is to structured data. You could add it with something like the following:-
pom.xml (Spring Boot starters also available)
<!-- Java API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-jpa</artifactId>
<version>0.9.0</version>
</dependency>
<!-- REST API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-rest</artifactId>
<version>0.9.0</version>
</dependency>
Configuration
@Configuration
@EnableJpaStores
@Import("org.springframework.content.rest.config.RestConfiguration.class") <!-- enables REST API)
public class ContentConfig {
<!-- specify the resource specific to your database -->
@Value("/org/springframework/content/jpa/schema-drop-h2.sql")
private ClasspathResource dropBlobTables;
<!-- specify the resource specific to your database -->
@Value("/org/springframework/content/jpa/schema-h2.sql")
private ClasspathResource createBlobTables;
@Bean
DataSourceInitializer datasourceInitializer() {
ResourceDatabasePopulator databasePopulator =
new ResourceDatabasePopulator();
databasePopulator.addScript(dropBlobTables);
databasePopulator.addScript(createBlobTables);
databasePopulator.setIgnoreFailedDrops(true);
DataSourceInitializer initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource());
initializer.setDatabasePopulator(databasePopulator);
return initializer;
}
}
NB: this configuration is not needed if you use the Spring Boot starters.
To associate content, add Spring Content annotations to your account entity.
Example.java
@Entity
public class Report {
// replace @Lob field with:
@ContentId
private String contentId;
@ContentLength
private long contentLength = 0L;
// if you have rest endpoints
@MimeType
private String mimeType = "text/plain";
Create a "store":
ExampleStore.java
@StoreRestResource(path="reportContent")
public interface ReportContentStore extends ContentStore<Report, String> {
}
This is all you need to create REST endpoints @ /reportContent
. When your application starts, Spring Content will look at your dependencies (seeing Spring Content JPA/REST), look at your ReportContentStore
interface and inject an implementation of that interface for JPA. It will also inject a @Controller
that forwards http requests to that implementation. This saves you having to implement any of this yourself.
So...
curl -X POST /reportsContent/{reportId}
-F ‘data=@path/to/local/file’
will store the content of path/to/local/file
in the database and associate it with the report entity whose id is reportId
.
curl /reportContent/{reportId}
will fetch it again and so on...supports full CRUD.
There are a couple of getting started guides and videos here. The reference guide is here.
HTH