2012-02-06 45 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()); 
}