How to reference GridFSFile with @DbRef annotation (spring data mongodb)

蓝咒 提交于 2019-12-13 14:34:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!