如何使用@DbRef注释引用GridFSFile(Spring Data MongoDB) [英] How to reference GridFSFile with @DbRef annotation (spring data mongodb)
问题描述
我有一个弹簧@Document object Profile
i have a spring @Document object Profile
我想像这样引用GridFSFile:
i would like to reference GridFSFile like it :
@DbRef
private GridFSFile file;
该文件被写入另一个集合类型GridFS.
the file is writen into another collection type GridFS.
设置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
谢谢, 泽维尔
推荐答案
我想要类似的东西,但没有找到方法,所以我采取了这种解决方法.
I wanted something similar, and didn't find a way, so I made this workaround.
在@Document类中,放置一个ObjectId
字段
In your @Document class, put a ObjectId
field
@Document
public class MyDocument {
//...
private ObjectId file;
}
然后在您的存储库中,按照来自Oliver Gierke的建议,并使用自定义方法,将文件链接到此MyDocument. GridFsTemplate
:
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);
}
}
}
顺便说一句,您需要在JavaConf中声明您的GridFsTemplate
以便自动装配
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());
}
这篇关于如何使用@DbRef注释引用GridFSFile(Spring Data MongoDB)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!