当前位置:   article > 正文

保存mongodb数据时出现_class字段,应该如何去掉

保存mongodb数据时出现_class字段,应该如何去掉

配置如下:
application.yml文件内容如下

spring:
  data:
    mongodb:
      host: 192.168.9.234 #指定MongoDB服务地址
      port: 27017 #指定端口,默认就为27017
      database: blog #指定使用的数据库(集合)
      authentication-database: admin # 登录认证的逻辑库名
      username: admin #用户名
      password: 123456 #密码
  main:
    banner-mode: off
server:
  port: 8080

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

公共类如下
IBasicDao类:

package com.zingrow.blog.common;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import java.util.List;

public interface IBasicDao<T> {
    /**
     * 查询数据
     *
     * @param query
     * @return
     */

    List<T> find(Query query);

    /**
     * 分页查询
     *
     * @param query
     * @param start
     * @param size
     * @return
     */
    List<T> findList(Query query, int start, int size);


    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    T findOne(String id);

    /**
     * 插入一条数据
     *
     * @param entity
     */
    void insert(T entity);

    /**
     * 更新数据
     *
     * @param query
     * @param update
     * @return
     */
    UpdateResult update(Query query, Update update);

    /**
     * 根据实体类删除数据
     *
     * @param entity
     * @return
     */
    DeleteResult delete(T entity);


    /**
     * 根据query删除数据
     *
     * @param query
     * @return
     */

    DeleteResult remove(Query query);

    long count();

    long count(Query query);

    void save(T entity);

    List<T> findAll();

    List<T> findByKeyAndValue(String key, String Value);

    List<T> findByKeyAndValue(String key, String Value, int start, int limit);

    void upsert(Query query, Update update);

    MongoTemplate getMongoTemplate();
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88

其实现类BasicDao内容如下

package com.zingrow.blog.common;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public class BasicDao<T> implements IBasicDao<T> {
    private Class<T> clazz;

    public BasicDao() {
        ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
        clazz = (Class<T>) type.getActualTypeArguments()[0];
    }

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<T> find(Query query) {
        return mongoTemplate.find(query, clazz);
    }

    @Override
    public List<T> findList(Query query, int start, int size) {
        query.with(Sort.by(new Sort.Order(Sort.Direction.ASC, "_id")))
                .skip(start)
                .limit(size);
        return mongoTemplate.find(query, clazz);
    }

    @Override
    public T findOne(String id) {
        Query query = new Query();
        query.addCriteria(new Criteria("_id").is(id));
        return mongoTemplate.findOne(query, clazz);
    }

    @Override
    public void insert(T entity) {
        mongoTemplate.insert(entity);
    }

    @Override
    public UpdateResult update(Query query, Update update) {
        return mongoTemplate.updateMulti(query, update, clazz);
    }

    @Override
    public DeleteResult delete(T entity) {
        return mongoTemplate.remove(entity);
    }

    @Override
    public DeleteResult remove(Query query) {
        return mongoTemplate.remove(query, clazz);
    }

    public DeleteResult remove(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("id").is(id));
        return mongoTemplate.remove(query, clazz);
    }

    @Override
    public long count() {
        Query query = new Query();
        return mongoTemplate.count(query, clazz);
    }

    @Override
    public long count(Query query) {
        return mongoTemplate.count(query, clazz);
    }

    @Override
    public void save(T entity) {
        mongoTemplate.save(entity);
    }

    @Override
    public List<T> findAll() {
        Query query = new Query();
        return find(query);
    }

    @Override
    public List<T> findByKeyAndValue(String key, String Value) {
        Query query = new Query(Criteria.where(key).is(Value));

        return mongoTemplate.find(query, clazz);
    }

    @Override
    public List<T> findByKeyAndValue(String key, String Value, int start, int limit) {
        Query query = new Query(Criteria.where(key).is(Value));
        query.skip(start).limit(limit);
        return mongoTemplate.find(query, clazz);
    }

    @Override
    public void upsert(Query query, Update update) {
        mongoTemplate.upsert(query, update, clazz);
    }

    @Override
    public MongoTemplate getMongoTemplate() {
        return mongoTemplate;
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117

实体类(Article)如下

package com.zingrow.blog.entity;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "article")
public class Article {

    @Id
    private String id;
    private String title;
    private String classify;
    private String content;
    private String time;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getClassify() {
        return classify;
    }

    public void setClassify(String classify) {
        this.classify = classify;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public Article(String id, String title, String classify, String content, String time) {
        this.id = id;
        this.title = title;
        this.classify = classify;
        this.content = content;
        this.time = time;
    }

    @Override
    public String toString() {
        return "Article{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                ", classify='" + classify + '\'' +
                ", content='" + content + '\'' +
                ", time='" + time + '\'' +
                '}';
    }
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74

服务实现类(ArticleServiceImpl)

package com.zingrow.blog.service;
import com.zingrow.blog.common.BasicDao;
import com.zingrow.blog.entity.Article;
import org.springframework.stereotype.Service;

@Service
public class ArticleServiceImpl extends BasicDao<Article> {
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

控制类(ArticleController)

package com.zingrow.blog.contronller;
import com.zingrow.blog.entity.Article;
import com.zingrow.blog.service.ArticleServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(value = "*", maxAge = 300)
public class ArticleController {
    @Autowired
    private ArticleServiceImpl articleService;
    @GetMapping("add")
    public String add(Article article) {
        articleService.insert(article);
        return article.toString();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

成功插入数据后
在这里插入图片描述
发现多了个_class字段,解决办法如下
新建配置类(MongoConfig)

package com.zingrow.blog.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.DbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

@Configuration
public class MongoConfig {

    @Bean(name = "mongoTemplate")
    public MongoTemplate mongoTemplate(MongoDatabaseFactory mongoDatabaseFactory, MongoMappingContext mongoMappingContext) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDatabaseFactory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, mongoMappingContext);
        //去掉_class字段
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return new MongoTemplate(mongoDatabaseFactory,mappingConverter);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

结果如下

在这里插入图片描述
失败案例:
新建配置类(在实际项目引入时可能会报MongoDbFactory已被废弃)


@Configuration
public class MongoConfig {
 
    @Bean
    public MappingMongoConverter mappingMongoConverter(MongoDbFactory factory, MongoMappingContext context, BeanFactory beanFactory) {
        DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
        MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
        try {
            mappingConverter.setCustomConversions(beanFactory.getBean(CustomConversions.class));
        } catch (NoSuchBeanDefinitionException ignore) {
        }
 
        // Don't save _class to mongo
        mappingConverter.setTypeMapper(new DefaultMongoTypeMapper(null));
        return mappingConverter;

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/140834
推荐阅读
相关标签
  

闽ICP备14008679号