Springboot 集成MongoDB
1、依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<version>3.0.6</version>
</dependency>
MongoDB使用的版本是7.0.3
2、配置
spring:
data:
mongodb:
host: localhost
port: 27017
database: 数据库名(test)
username: admin
password:
- '1'
- '2'
- '3'
- '4'
- '5'
- '6'
auto-index-creation: true #创建索引开关打开,默认关闭
gridfs:
bucket: fs2 #自定义bucket名称
3、调用MongoDB方法
- 自定义接口实现MongoRepository<T,ID>
其中T表示实体类,ID表示存储中实体id的类型
public interface UserMongoRepo extends MongoRepository<User,Object> {
}
@Autowired
private UserMongoRepo userMongoRepo;
public Object test0(){
List<User> all = userMongoRepo.findAll();
return all;
}
- MongoTemplate使用
@Autowired
private MongoTemplate mongoTemplate;
public Object test1(@PathVariable("name") String name,@PathVariable("age") int age){
//where name=张三 and age=20
Query andQuery = new Query();
andQuery.addCriteria(Criteria.where("name").is(name).and("age").gt(age));
andQuery.with(Sort.by(Sort.Order.desc("age")));
List<User> users = mongoTemplate.find(andQuery, User.class);
System.out.println("and查询:"+users);
//where name=张三 and (age>20 or 1=1 )
Query orQuery = new Query();
orQuery.addCriteria(Criteria.where("name").is(name).orOperator(Criteria.where("age").gt(age)));
orQuery.with(Sort.by(Sort.Order.desc("age")));
List<User> orUsers = mongoTemplate.find(orQuery, User.class);
System.out.println("or查询:"+orUsers);
Query Query = new Query();
Query.fields().exclude("_id");
Query.fields().exclude("birth");
Query.fields().exclude("phone");
//where name=张三 or age>20
Query.addCriteria(new Criteria().orOperator(Criteria.where("name").is(name),Criteria.where("age").gt(age)));
Query.with(Sort.by(Sort.Order.desc("age")));
List<Map> users1 = mongoTemplate.find(Query, Map.class,"users");
System.out.println("or查询:"+users1);
return users1;
}
- GridFsTemplate 使用
使用GridFsTemplate进行文件的上传、下载、删除、查看基本信息
@Autowired
GridFsTemplate gridFsTemplate; //GridFsOperations implementation to store content into MongoDB GridFS.
@Autowired
GridFSBucket gridFSBucket; //Represents a GridFS Bucket
//上传文件
@PostMapping("/upload")
public Object upload(MultipartFile file) throws IOException {
//文件名称
String filename = file.getOriginalFilename();
//文件输入流
InputStream inputStream = file.getInputStream();
//文件类型
String contentType = file.getContentType();
//上传文件中使用BasicDBObject添加一些属性
DBObject metaDate = new BasicDBObject();
metaDate.put("key", "hello mongodb");
//MongoDB存储图片、视频
ObjectId id = gridFsTemplate.store(inputStream, filename, contentType, metaDate);
log.debug("文件id:{}", id);
return id.toString();
}
//获取文件基本信息(不包括图片内容)
@GetMapping("/getFile")
public Object getFile(@RequestParam("id") String fileId, @RequestParam("name") String name) {
Query query = new Query();
Criteria id = Criteria.where("_id").is(fileId);
Criteria filename1 = Criteria.where("filename").is(name);
// Criteria criteria = new Criteria().orOperator(id, filename1);
query.addCriteria(new Criteria().orOperator(Criteria.where("filename").is(name),Criteria.where("filename").is(name)));
//查找文件(图片、视频等)信息
GridFSFile gridFSFile = gridFsTemplate.findOne(query);
if (gridFSFile == null) {
return "文件不存在";
}
String filename = gridFSFile.getFilename();
log.debug("文件名称:{}", filename);
Object meta = gridFSFile.getMetadata().get("key");
log.debug("meta属性值:{}", meta);
return gridFSFile.toString();
}
//下载文件
@GetMapping("/download")
public void download(@RequestParam("id") String fileId, @RequestParam("name") String name, HttpServletResponse response) throws IOException {
Query query = new Query();
//更具file_id 或 文件名称 下载文件
query.addCriteria(new Criteria().orOperator(Criteria.where("_id").is(fileId),Criteria.where("filename").is(name)));
GridFSFile gridFSFile = gridFsTemplate.findOne(query);
if (gridFSFile == null) {
//文件不存在
log.debug("文件不存在,id:{}", fileId);
return;
}
//解决中文乱码
String fileName = new String(gridFSFile.getFilename().getBytes("GBK"), "ISO-8859-1");
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
GridFSDownloadStream gridFSDownloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
//创建GridFsResource,获取流对象
GridFsResource resource = new GridFsResource(gridFSFile, gridFSDownloadStream);
InputStream inputStream = resource.getInputStream();
ServletOutputStream outputStream = response.getOutputStream();
byte[] bytes = new byte[1024];
int len;
while ((len = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, len);
}
inputStream.close();
}
//删除文件
@GetMapping("/delFile")
public void delFile(@RequestParam("id") String fileId) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(fileId));
GridFSFile gridFSFile = gridFsTemplate.findOne(query);
if (gridFSFile == null) {
//文件不存在
log.debug("文件不存在,id:{}", fileId);
return;
}
ObjectId objectId = gridFSFile.getObjectId();
gridFsTemplate.delete(query);
log.debug("文件删除成功,文件id:{}", fileId);
}
自定义配置文件中定义GridFSBucket
@Value("${spring.data.mongodb.database}")
private String dbName;
@Value("${spring.data.mongodb.gridfs.bucket:fs}")
private String bucketName;
@Bean
public GridFSBucket gridFSBucket(MongoClient client) {
MongoDatabase database = client.getDatabase(dbName);
GridFSBucket gridFSBucket = GridFSBuckets.create(database,bucketName);
return gridFSBucket;
}
}
- 自定义实体类
@Data
@Document(value = "users") //创建集合名称
@ToString
@CompoundIndex(def="{'age':1,'phone':-1}") //创建复合索引
@Accessors(chain = true)
public class User {
// @MongoId(FieldType.OBJECT_ID)
// @Field("_id")
// private Object id;
@Indexed(name = "index_name")
private String name;
private int age;
private String phone;
private String addr;
private Date birth;
}
其中
@CompoundIndex 创建复合索引;
@Indexed(name = "index_name") 创建单索引;
@Document(value = "users") 创建集合名称;
4、源码简单说明
MongoDataAutoConfiguration.java 引入Configuration类
@AutoConfiguration(after = MongoAutoConfiguration.class)
@ConditionalOnClass({ MongoClient.class, MongoTemplate.class })
@EnableConfigurationProperties(MongoProperties.class)
@Import({ MongoDataConfiguration.class, MongoDatabaseFactoryConfiguration.class,
MongoDatabaseFactoryDependentConfiguration.class })
public class MongoDataAutoConfiguration {
}
MongoDatabaseFactoryDependentConfiguration.java 定义需要的bean
@Configuration(proxyBeanMethods = false)
@ConditionalOnBean(MongoDatabaseFactory.class)
class MongoDatabaseFactoryDependentConfiguration {
private final MongoProperties properties;
MongoDatabaseFactoryDependentConfiguration(MongoProperties properties) {
this.properties = properties;
}
@Bean
@ConditionalOnMissingBean(MongoOperations.class)
MongoTemplate mongoTemplate(MongoDatabaseFactory factory, MongoConverter converter) {
return new MongoTemplate(factory, converter);
}
@Bean
@ConditionalOnMissingBean(MongoConverter.class)
MappingMongoConverter mappingMongoConverter(MongoDatabaseFactory factory, MongoMappingContext context,
MongoCustomConversions conversions) {
DbRefResolver dbRefResolver = new DefaultDbRefResolver(factory);
MappingMongoConverter mappingConverter = new MappingMongoConverter(dbRefResolver, context);
mappingConverter.setCustomConversions(conversions);
return mappingConverter;
}
@Bean
@ConditionalOnMissingBean(GridFsOperations.class)
GridFsTemplate gridFsTemplate(MongoDatabaseFactory factory, MongoTemplate mongoTemplate) {
return new GridFsTemplate(new GridFsMongoDatabaseFactory(factory, this.properties),
mongoTemplate.getConverter(), this.properties.getGridfs().getBucket());
}
...
}