spring boot在集成MongoDB的时候,根据spring boot版本集成方式也不太一样,我在集成的时候遇到的情况就是在2.0简化的集成方式放在1.0的时候不能用,我就把我集成的两种方式都介绍一下。
一 、 spring boot2.0集成方式:
1、引入MongoDB jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、在application.properties配置文件中设置:
spring.data.mongodb.host=192.168.3.249
spring.data.mongodb.port=27017
spring.data.mongodb.username=ceshi
spring.data.mongodb.password=123456
spring.data.mongodb.database=huahan
二、spring boot1.0集成方式:
1、引入MongoDB jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2、在resource下创建配置文件database.properties
mongodb.uri=192.168.3.249:27017
mongodb.username=ceshi
mongodb.password=123456
mongodb.schema=huahan
3、创建MongoDBConfig配置类
@Configuration
@PropertySource(value = "classpath:database.properties",ignoreResourceNotFound = true)
public class MongoDBConfig {
@Value("${mongodb.schema}")
private String databaseName;
@Value("${mongodb.uri}")
private String uri;
@Value("${mongodb.username}")
private String userName;
@Value("${mongodb.password}")
private String password;
@Bean
public MongoDbFactory mongoDbFactory() throws UnknownHostException {
String uriStr="mongodb://"+userName+":"+password+"@"+uri+"/"+databaseName;
System.out.println(uriStr);
MongoClientURI mongoClientURI=new MongoClientURI(uriStr);
MongoDbFactory mongoDbFactory=new SimpleMongoDbFactory(mongoClientURI);
return mongoDbFactory;
}
}
三、MongoDB的使用
1、创建model类,MongoDB不需要创建表,直接创建实体类即可
@Component
@Getter
@Setter
public class OperationLog {
/**
* 日志类型
*/
private String logtype;
/**
* 日志名称
*/
private String logname;
/**
* 用户id
*/
private Integer userid;
/**
* 类名称
*/
private String classname;
/**
* 方法名称
*/
private String method;
/**
* 创建时间
*/
private Date createtime;
/**
* 是否成功
*/
private String succeed;
/**
* 备注
*/
private String message;
}
2、mongoTemplate查询实例
@RestController
@RequestMapping(value = "/mongodb")
public class MongodbController {
@Autowired
private MongoTemplate mongoTemplate;
@RequestMapping(value = "/getName")
public Object getName(){
String name = mongoTemplate.getDb().getName();
return name;
}
@RequestMapping(value = "/getLog")
public Object getLog(){
Integer currentPage = 1;
Integer pageSize = 10;
Query query = new Query();
query.with(new Sort(Sort.Direction.DESC,"createtime"));
query.skip((currentPage-1)*pageSize);
query.limit(pageSize);
List<OperationLog> logs = mongoTemplate.find(query,OperationLog.class);
return logs;
}
}
网友评论