1、pom依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>

2、application配置

spring:    
   mongodb:
      uri: mongodb://name:password@localhost:27017/test

name为mongodb的用户名,password为mongodb的密码

3、项目集成

    @Autowired
    public MongoTemplate mongoTemplate;

4、使用

4.1、实体类

@Document(collection = "tes_namespace")
public class Namespace extends AbstractEntity{

	/**
	 * 
	 */
	private static final long serialVersionUID = 4531499444309419351L;

	@Field("name")
	private String name;

	@Field("code")
	private String code;

	@Field("description")
	private String description;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getCode() {
		return code;
	}

	public void setCode(String code) {
		this.code = code;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}
}

@Document用于指定数据库的conllection

@field用于指定数据库字段

@id用于标识主键

@GeneratedValue 自动生成id

4.2、使用

4.2.1、新增

public int addNamespace(Namespace namespace) {
		mongoTemplate.save(namespace);
		return 1;
	}

4.2.2、查询,分页

public List<Namespace> queryNamespace(String name,String code,Integer offset,Integer limit) {
		Query query = new Query();
		if(StringUtils.isNotEmpty(name)){
			query.addCriteria(Criteria.where("name").is(name));
		}
		if (StringUtils.isNotEmpty(code)) {
			query.addCriteria(Criteria.where("code").is(code));
		}
		query.with(new Sort(new Sort.Order(Sort.Direction.DESC, "creatTime")));
		int skip = (offset - 1) * limit;
		query.skip(skip);// 从那条记录开始
		query.limit(limit);// 取多少条记录
		List<Namespace> list = mongoTemplate.find(query,Namespace.class);
		return list;
	}


4.2.3、修改

public int updateNamespace(Namespace namespace) {
		Query query = new Query();
		query.addCriteria(Criteria.where("id").is(namespace.getId()));
		Update update = new Update();
		if(StringUtils.isNotEmpty(namespace.getName())) {
			update.set("name",namespace.getName());
		}
		if(StringUtils.isNotEmpty(namespace.getCode())){
			update.set("code",namespace.getCode());
		}
		if(StringUtils.isNotEmpty(namespace.getDescription())){
			update.set("description",namespace.getCode());
		}
		mongoTemplate.updateFirst(query, update, Namespace.class);
		return 1;
	}


4.2.4、删除

public int delNamespace(String id) {
		Query query=new Query(Criteria.where("id").is(id));
		mongoTemplate.remove(query,Namespace.class);
		return 1;
	}


4.2.5、单个查询

public Namespace queryNamespaceById(String id) {
		Query query = new Query();
		query.addCriteria(Criteria.where("id").is(id));
		Namespace namespace = mongoTemplate.findOne(query,Namespace.class);
		return namespace;
	}


Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐