How to reference GridFSFile with @DbRef annotation (spring data mongodb)

i has spring @Document object Profile

I would like to reference the GridFSFile:

 @DbRef private GridFSFile file; 

the file is written to another type of GridFS collection.

I always have java.lang.StackOverflowError when I set profile.setFile(file);

 java.lang.StackOverflowError at org.springframework.util.ObjectUtils.nullSafeHashCode(ObjectUtils.java:336) at org.springframework.data.util.TypeDiscoverer.hashCode(TypeDiscoverer.java:365) at org.springframework.data.util.ClassTypeInformation.hashCode(ClassTypeInformation.java:39) at org.springframework.util.ObjectUtils.nullSafeHashCode(ObjectUtils.java:336) at org.springframework.data.util.ParentTypeAwareTypeInformation.hashCode(ParentTypeAwareTypeInformation.java:79) at org.springframework.util.ObjectUtils.nullSafeHashCode(ObjectUtils.java:336) 

I donโ€™t understand if someone with an idea refers to a file that interests me

Thanks, Xavier

+4
source share
1 answer

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 { //... private ObjectId file; } 

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()); } 
+1
source

Source: https://habr.com/ru/post/1395072/


All Articles