spring boot1.5.2整合spring data mongodb10.1

教程分享 > Java教程 > Spring (8632) 2024-08-07 11:05:25
Java编程中使用spring boot1.5.2框架整合spring data mongodb10.1,来使用mongodb数据库

项目结构图:
项目结构图
本项目主要讲解spring整合mongodb后的一些基本操作,如新增数据,修改数据,删除数据,查询数据

代码清单:
定义一个简单的pojo Customer.java:
package com.leftso.entity;

/**
 * 测试用类
 * 
 * @author leftso
 *
 */
// @Document
public class Customer {

	private String id;
	private String firstName;
	private String lastName;

	public Customer() {

	}

	public Customer(String firstName, String lastName) {
		this.firstName = firstName;
		this.lastName = lastName;
	}

	@Override
	public String toString() {
		return String.format("Customer[id=%s, firstName='%s', lastName='%s']", id, firstName, lastName);
	}
}

添加数据配置mongo.properties:
#DB host+port,Multiple host separation with ','
db.host=localhost:27017
#DB name
db.name=test1
#DB User Name
db.user=
#DB User Password
db.pwd=

自定义配置mongodb的数据源
数据库配置文件MongoProperty.java:
package com.leftso.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * mongodb的配置文件载入
 * 
 * @author leftso
 *
 */
@Component
@ConfigurationProperties(prefix = "db")
@PropertySource("classpath:mongo.properties")
public class MongoProperty {
	/** 主机地址IP+端口 **/
	private String host;
	/** 数据库名称 ***/
	private String name;
	/** 数据库用户(非必须) ***/
	private String user;
	/** 数据库密码 **/
	private String pwd;

	public String getHost() {
		return host;
	}

	public void setHost(String host) {
		this.host = host;
	}

	public String getName() {
		return name;
	}

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

	public String getUser() {
		return user;
	}

	public void setUser(String user) {
		this.user = user;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

}

数据源MongoDBConfig.java:
package com.leftso.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.util.StringUtils;

import com.mongodb.MongoClient;
import com.mongodb.MongoClientURI;

/**
 * mongodb 配置类
 * 
 * @author leftso
 *
 */
@Configuration
public class MongoDBConfig {
	@Autowired
	MongoProperty mongoProperties;

	/**
	 * 注入mongodb的工厂类
	 * 
	 * @return
	 */
	@Bean
	public MongoDbFactory mongoDbFactory() {
		// uri格式mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
		String mongoURI = "mongodb://" + mongoProperties.getHost();
		if (!StringUtils.isEmpty(mongoProperties.getUser())) {
			mongoURI = "mongodb://" + mongoProperties.getUser() + ":" + mongoProperties.getPwd() + "@"
					+ mongoProperties.getHost();
		}
		// 为了方便实现mongodb多数据库和数据库的负债均衡这里使用url方式创建工厂
		MongoClientURI mongoClientURI = new MongoClientURI(mongoURI);
		MongoClient mongoClient = new MongoClient(mongoClientURI);
		MongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(mongoClient, mongoProperties.getName());
		// 注意:以下构造函数已经弃用:
		// SimpleMongoDbFactory(com.mongodb.Mongo mongo, String databaseName);
		// 弃用版本1.7
		// SimpleMongoDbFactory(com.mongodb.Mongo mongo, String databaseName,
		// UserCredentials credentials);弃用版本1.7
		// SimpleMongoDbFactory(com.mongodb.Mongo mongo, String databaseName,
		// UserCredentials credentials, String
		// authenticationDatabaseName);弃用版本1.7
		// SimpleMongoDbFactory(com.mongodb.MongoURI uri);弃用版本1.7
		return mongoDbFactory;
	}

	/**
	 * 获取操作实例
	 * 
	 * @param mongoDbFactory
	 * @return
	 */
	@Bean
	public MongoTemplate mongoTemplate(MongoDbFactory mongoDbFactory) {
		return new MongoTemplate(mongoDbFactory);
	}

}

创建customer的简单存储操作类
基于spring data框架的方式CustomerMongoRepository.java

 
package com.leftso.repository;

import java.util.List;

import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

import com.leftso.entity.Customer;

/**
 * spring data提供接口方式实现简单的操作,通常适合简单的或者测试用
 * 
 * @author leftso
 *
 */
@Repository
public interface CustomerMongoRepository extends MongoRepository<Customer, String> {

	public Customer findByFirstName(String firstName);

	public List<Customer> findByLastName(String lastName);
}

自定义方式实现CustomizeCustomerMongoRepository.java
 
package com.leftso.repository;

import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
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.stereotype.Repository;

import com.leftso.entity.Customer;

/**
 * 自定义数据存储方式
 * 
 * @author leftso
 *
 */
@Repository
public class CustomizeCustomerMongoRepository {

	@Autowired
	MongoTemplate mongoTemplate;

	/**
	 * 保存一个对象
	 * 
	 * @return
	 */
	public Customer save(Customer customer) {
		mongoTemplate.save(customer);
		return customer;
	}

	/**
	 * 删除所有
	 */
	public void deleteAll() {
		mongoTemplate.dropCollection(Customer.class);
	}

	/**
	 * 查询所有
	 * 
	 * @return
	 */
	public List<Customer> findAll() {
		return mongoTemplate.findAll(Customer.class);
	}

	/**
	 * 精确查询
	 * 
	 * @param firstName
	 * @return
	 */
	public List<Customer> findByFirstName(String firstName) {
		Query query = new Query();
		query.addCriteria(Criteria.where("firstName").is(firstName));

		return mongoTemplate.find(query, Customer.class);
	}

	/**
	 * 模糊查询不区分大小写
	 * 
	 * @param lastName
	 * @return
	 */
	public List<Customer> findByLastName(String lastName) {
		Query query = new Query();
		Pattern pattern = Pattern.compile("^.*" + lastName + ".*$", Pattern.CASE_INSENSITIVE);// Pattern.CASE_INSENSITIVE不区分大小写
		query.addCriteria(Criteria.where("lastName").regex(pattern));
		return mongoTemplate.find(query, Customer.class);
	}

}

项目源码下载:
https://github.com/leftso/demo-spring-boot-mongodb
 
https://www.leftso.com/article/135.html

相关文章
Java编程中使用spring boot1.5.2框架整合spring data mongodb10.1,来使用mongodb数据库
Java编程中Spring Boot整合RabbitMQ实现消息中间件RabbitMQ的使用
Java编程中spring boot项目如何获取spring容器applicationContext
Java编程之Spring Boot通过JMSTemplate 整合ActiveMQ
Java编程之Spring Boot 使用SLF4J Logging,spring boot,SLF4J
1.引言Spring 5通过引入一种名为Spring WebFlux的全新反应框架来支持响应式编程范例
Java编程中spring boot项目动态添加拦截器Interceptor
Java编程之spring boot shiro redis整合基于角色和权限的安全管理,Java编程,spring boot,shiro,权限控制
spring boot 入门之security oauth2 jwt完美整合例子,Java编程中spring boot框架+spring security框架+spring security o...
Java编程之spring boot FastDFS Java client使用,Java编程,FastDFS Java客户端
Spring data-mongodb ID自增长注解实现,mongodb ID自增长
java编程为啥会出现spring框架,为什么要有Spring?
spring boot mybatis 整合使用讲解介绍,spring boot与MyBatis的使用讲解介绍。spring boot mybatis xml mapper方式的入门和通过一个简...
spring boot整合activemq。本博客将通过一个简单的例子讲解在spring boot中activemq如何作为消费者(Consumer )和如何在spring boot中消息提供者...
Java编程之Spring Boot 文件上传 REST风格API ajax方式