2012-02-06 43 views
4

我有一個春天@Document object Profile如何引用GridFSFile與@DbRef註釋(春季數據的MongoDB)

我想引用GridFSFile喜歡它:

@DbRef 
private GridFSFile file; 

文件被writen到另一個集合鍵入GridFS。

我一直有一個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) 

我不明白,如果有人有一個想法,引用文件我感興趣

感謝, 澤維爾

回答

1

我想要類似的東西,並沒有找到辦法,所以我做了這個解決方法。

在你@Document類,把ObjectId

@Document 
public class MyDocument { 
    //...  
    private ObjectId file; 
} 

然後在你的存儲庫,添加自定義方法,以文件鏈接到這個myDocument中,以下advices from Oliver Gierke和使用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以自動裝載它

@Bean 
public GridFsTemplate gridFsTemplate() throws Exception { 
    return new GridFsTemplate(mongoDbFactory(), mappingMongoConverter()); 
}