'How to configure collections other than fs.files fs.chunks in GridFsTemplate in MongoDB
GridFsTemplate insertes data in collections:fs.files and fs.chunks. Is there any way to make GridFsTemplate use my own collections?
e.g. In my project, I need to dump all files in attachments.files and attachments.chunks.
I am able to do it using just GridFs like this:
DB mongoDB = mongoDbFactory.getDb();
GridFS fileStore = new GridFS(mongoDB, "attachment");
but I would like to do it by @autowire GridFsTemplate, perform operations like gridFsTemplate.store(file, filename), and it should dump data in my own collections.
Solution 1:[1]
To be able to Autowire it with a default Bucket, you can define a Bean for it in Mongo Client Configuration. It goes something like this:
Create a configuration class->
@Configuration
public class MongoConnectionConfig extends AbstractMongoClientConfiguration {
//store this in application.properties file 'mongo.file-system-bucket.attachment=attachment'
@Value("${mongo.file-system-bucket.attachment}")
private String bucketAttachment;
//store this in application.properties file 'mongo.file-system-bucket.image=image'
@Value("${mongo.file-system-bucket.image}")
private String bucketImage;
@Autowired
private MappingMongoConverter mongoConverter;
@Bean(name = "gridFsTemplateAttachments")
public GridFsTemplate gridFsTemplate() throws Exception {
return new GridFsTemplate(mongoDbFactory(), mongoConverter, bucketAttachment);
}
@Bean(name = "gridFsTemplateImages")
public GridFsTemplate gridFsTemplate() throws Exception {
return new GridFsTemplate(mongoDbFactory(), mongoConverter, bucketImage);
}
}
Now to use these Beans you can Autowire them in your DAO and work with different buckets as per your requirements.
Eg. ->
@Repository
public class AssetTransactionsDAO implements AssetTransactionsInterface {
@Autowired
private GridFsTemplate gridFsTemplateImages;
@Autowired
private GridFsTemplate gridFsTemplateAttachments;
@Override
public String insertAttachment(AttachementModel attachment){
//do your stuff gridFsTemplateAttachments.store(.....)
return "";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
