![](/img/trans.png)
[英]Spring-Data for MongoDB exception while using @DBRef annotation for referencing
[英]How to reference GridFSFile with @DbRef annotation (spring data mongodb)
我有一個spring @Document object Profile
我想像它一樣引用GridFSFile:
@DbRef
private GridFSFile file;
該文件被寫入另一個集合類型GridFS。
當我設置profile.setFile(file);
時,我總是有一個java.lang.StackOverflowError
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)
我不明白,如果有人有想法引用我感興趣的文件
謝謝,澤維爾
我想要類似的東西,並沒有找到方法,所以我做了這個解決方法。
在@Document類中,放置一個ObjectId
字段
@Document
public class MyDocument {
//...
private ObjectId file;
}
然后在您的存儲庫中, 根據Oliver GridFsTemplate
建議並使用GridFsTemplate
,將自定義方法添加到鏈接文件到此MyDocument:
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
以自動裝配它
@Bean
public GridFsTemplate gridFsTemplate() throws Exception {
return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.