I wanted something similar, and could not find a way, so I made this workaround.
In your @Document class, put an ObjectId field
@Document public class MyDocument {
Then in your repository add your own method for linking the file to this MyDocument, following the advice from Oliver Gierke and using the GridFsTemplate :
public class MyDocumentRepositoryImpl implements MyDocumentRepositoryCustom { public static final String MONGO_ID = "_id"; @Autowired GridFsTemplate gridFsTemplate; @Override public void linkFileToMyDoc(MyDocument myDocument, InputStream stream, String fileName) { GridFSFile fsFile = gridFsTemplate.store(stream, fileName); myDocument.setFile( (ObjectId) fsFile.getId()); } @Override public void unLinkFileToMyDoc(MyDocument myDocument) { ObjectId objectId = myDocument.getFile(); if (null != objectId) { gridFsTemplate.delete( Query.query(Criteria.where(MONGO_ID).is(objectId)) ); myDocument.setFile(null); } } }
By the way, you need to declare your GridFsTemplate in your JavaConf in order to auto-convert it.
@Bean public GridFsTemplate gridFsTemplate() throws Exception { return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter()); }
source share