Springboot集成mongodb
# pom文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
1
2
3
4
2
3
4
# yml文件
spring:
data:
mongodb:
database: imgdb
repositories:
enabled: true
port: 27017
host: 192.168.213.213
username: iadmin
password: iadmin27017
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 代码使用
# 增加MgTemplate的Class文件
package cn.ok96.common;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.stereotype.Component;
import com.mongodb.client.MongoCollection;
@Component("mgTemplate")
public class MgTemplate {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 添加数据
* @param collectionName
* @return
*/
public MongoCollection<Document> getCollection(String collectionName) {
return mongoTemplate.getCollection(collectionName);
}
/**
*
* 查找数据
* @param imageId
* @return Image实体类
*/
public Image findOne(String imageId) {
Query query = new Query()
.addCriteria(Criteria.where("imgId").is(imageId));
return mongoTemplate.findOne(query, Image.class);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# 在使用类中引用-插入数据
public class imclass {
@Autowired
private MgTemplate mgTemplate;
public String test(String rawPass) {
String id = new ObjectId().toString();
Document document = new Document();
document.put("img","dasdasd");
document.put("imgId", id);
document.put("createTime", DateUtil.forFull(new Date()));
mgTemplate.getCollection("imgInfo").insertOne(document);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 在使用类中引用-查找数据
# 创建实体类
package cn.ok96.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Data;
@Data
@Document(collection = "imgInfo")
public class Image {
private String imgId;
private String img;
private String createTime;
public String getImgId() {
return imgId;
}
public void setImgId(String imgId) {
this.imgId = imgId;
}
public String getImg() {
return img;
}
public void setImg(String img) {
this.img = img;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 在使用类中使用
public class imclass {
@Autowired
private MgTemplate mgTemplate;
@Override
public String getFaceForMongo(String id) {
Image face=mgTemplate.findOne(id);
return face.getImg();
}
}
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
上次更新: 2023/03/10, 09:02:56