例如:
我想存储员工的详细信息,比如
private Long id;
private String Name;
private String country;
现在,我还想在MongoDB中存储一个图像和上面的数据。
在我的控制器中,我写了下面的代码
Employee employee2 = new Employee();
employee2.setEmpId(1002);
employee2.setEmpName("Dinesh Rajput");
employee2.setCountry("India");
mongoOperations.save(employee2);
员工数据在DB中创建。现在如何将图像与其一起存储。
发布于 2018-02-14 22:46:06
您可以像下面这样添加代码
DBObject metaData = new BasicDBObject();
metaData.put("mobileNo", mobileNo);
metaData.put("FileName", fileName);
metaData.put("createDate", new Date());
发布于 2018-05-11 11:21:08
假设您正在使用Spring Boot,Spring Data Mongo,那么您应该考虑使用Spring Content for Mongo作为内容存储部分,如下所示:
将以下依赖项添加到pom.xml
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-mongo-boot-starter</artifactId>
<version>0.0.10</version>
</dependency>
<dependency>
<groupId>com.github.paulcwarren</groupId>
<artifactId>spring-content-rest-boot-starter</artifactId>
<version>0.0.10</version>
</dependency>
确保您的应用程序上下文中存在一个GridFsTemplate bean。类似于以下内容:
@Configuration
public class MongoConfig
@Bean
public GridFsTemplate gridFsTemplate() throws Exception {
return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
}
...
要允许内容与您的Employee实体相关联,请为其提供以下属性:
@ContentId
private String contentId;
@ContentLength
private long contentLength = 0L;
@MimeType
private String mimeType = "text/plain";
添加一个store接口:
@StoreRestResource(path="employeeImages")
public interface EmployeeImageStore extends ContentStore<Employee, String> {
}
这就是你所需要的。当您的应用程序启动时,Spring Content将看到Mongo/REST模块上的依赖项,它将为GridF注入EmployeeImageStore
存储的实现,以及支持完整CRUD功能的控制器的实现,并将这些操作映射到底层存储接口上。REST端点将在/employeeImages
下可用。
即
curl -X PUT /employeeImages/{employeeId}
将创建或更新员工的图像
curl -X GET /employeeImages/{employeeId}
将获取该员工的图像
curl -X DELETE /employeeImages/{employeeId}
将删除该员工的图像
here有几个入门指南。它们将Spring内容用于文件系统,但这些模块是可互换的。Mongo参考指南是here。还有一个教程视频here。
HTH
https://stackoverflow.com/questions/47011871
复制相似问题