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