问题
i have a spring @Document object Profile
i would like to reference GridFSFile like it :
@DbRef
private GridFSFile file;
the file is writen into another collection type GridFS.
I always have a 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 do not understand, if someone with an idea to reference a file I'm interested
Thanks, Xavier
回答1:
I wanted something similar, and didn't find a way, so I made this workaround.
In your @Document class, put a ObjectId
field
@Document
public class MyDocument {
//...
private ObjectId file;
}
Then in your Repository, add custom method to link file to this MyDocument, following advices from Oliver Gierke and using a 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'll need to declare your GridFsTemplate
in your JavaConf to autowire it
@Bean
public GridFsTemplate gridFsTemplate() throws Exception {
return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
}
来源:https://stackoverflow.com/questions/9165117/how-to-reference-gridfsfile-with-dbref-annotation-spring-data-mongodb