你应该看看社区项目Spring Content。该项目为您提供了一个类似于 Spring Data 的 API 和内容开发方法。它是非结构化数据(文档、图像、视频等),Spring Data 是结构化数据。您可以使用以下内容添加它:-
pom.xml(也可以使用 Spring Boot 启动器)
<!-- Java API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-jpa</artifactId>
<version>1.0.0.M10</version>
</dependency>
<!-- REST API -->
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-rest</artifactId>
<version>1.0.0.M10</version>
</dependency>
配置
@Configuration
// enables Java API
@EnableJpaStores
// enables REST API
@Import("org.springframework.content.rest.config.RestConfiguration.class")
public class ContentConfig {
// specify the resource specific to your database
@Value("/org/springframework/content/jpa/schema-drop-postgresql.sql")
private ClasspathResource dropBlobTables;
// specify the resource specific to your database
@Value("/org/springframework/content/jpa/schema-postgresql.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;
}
}
注意:如果您使用相关的 Spring Boot 启动器,则不需要此配置。
要关联内容,请将 Spring Content 注释添加到您的 User 实体。
用户.java
@Entity
public class User {
...
// replace @Lob/byte array field with:
@ContentId
private String contentId;
@ContentLength
private long contentLength = 0L;
@MimeType
private String mimeType;
为您的图片创建头像“商店”:
AvatarStore.java
public interface AvatarStore extends ContentStore<User, String> {
}
这就是创建响应内容类型的 REST 端点 @/users/{userId} 所需的全部内容。当您的应用程序启动时,Spring Content 将查看您的依赖项(查看 Spring Content JPA/REST),查看您的 AvatarStore 接口并为 JPA 注入该接口的实现。它还将注入一个@Controller,将http请求转发到该实现。这使您不必自己实现任何这些。
所以...
curl -X POST /users/{userId} -F 'file=@path/to/local/file.jpg'
会将头像path/to/local/file.jpg存储在数据库中,并将其与ID为userId的User实体关联。
curl /users/{usersId} -H 'Accept: image/jpg'
将再次获取它,依此类推...支持完整的 CRUD(顺便说一句,视频流也支持)
有入门指南和视频here。 Spring Content JPA 的参考指南是here。
HTH