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

时间:2024-02-21 20:21:12

配置如下:
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

公共类如下
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();
}

其实现类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;
    }
}

实体类(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 + '\'' +
                '}';
    }
}

服务实现类(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> {
}

控制类(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();
    }
}

成功插入数据后
在这里插入图片描述
发现多了个_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);
    }
}

结果如下

在这里插入图片描述
失败案例:
新建配置类(在实际项目引入时可能会报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;