目录
实体类准备,添加注解@Document与mongodb中的集合对应上;
官方文档: MongoDbFactory (Spring Data MongoDB 3.4.1 API)https://docs.spring.io/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/MongoDbFactory.htmlMongoTemplate (Spring Data MongoDB 3.4.1 API)https://docs.spring.io/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/MongoTemplate.htmlSpring Data MongoDB - Reference Documentationhttps://docs.spring.io/spring-data/mongodb/docs/2.1.10.RELEASE/reference/html/
Mongodb快速入门案例
创建项目:mongodb-demo:
pom文件:
<!-- 继承Spring boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.5.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
</dependency>
</dependencies>
applicaton.yml
位置:
内容:
server:
port: 9001
spring:
application:
name: mongo-demo
引导类:
位置:
内容:
package com.itheima.mongo;
@SpringBootApplication
public class MongoApplication {
public static void main(String[] args) {
SpringApplication.run(MongoApplication.class, args);
}
}
集成mongodb:
创建配置文件mongo.properties:
位置:resources资源文件夹下;
内容的逻辑:
- 主机地址:
- mongo.host=192.168.200.130
- 端口号:
- mongo.port=27017
- 数据库:
- mongo.dbname=leadnews-comment
内容:
#主机地址
mongo.host=192.168.200.130
#端口号
mongo.port=27017
#数据库
mongo.dbname=leadnews-comment
添加配置,创建类MongoDBconfigure:
位置:config包内;
内容的逻辑:
- 表示这是一个配置信息类:
- @Configuration
- 扫描配置文件:
- @PropertySource("classpath:mongo.properties")
- 能读一个方法中的所有属性:
- prefix是前缀,用于匹配配置文件中的内容,就是,配置文件中mongo.才会被读取;
- @ConfigurationProperties(prefix = "mongo")
- 自己构建MongoTemplate:
- public MongoTemplate getMongoTemplate()
- 如果有用户名和密码也可以通过MongoClient其他构造函数传参
- public SimpleMongoDbFactory getSimpleMongoDbFactory()
内容:
package com.itheima.mongo.config;
@Data
// 表示这是一个配置信息类;
@Configuration
// 扫描配置文件
@PropertySource("classpath:mongo.properties")
// 能读一个方法中的所有属性
// prefix是前缀,用于匹配配置文件中的内容,就是,配置文件中mongo.才会被读取
@ConfigurationProperties(prefix = "mongo")
public class MongoDBconfigure {
private String host;
private Integer port;
private String dbname;
/**
* 自己构建MongoTemplate
*
* @return
*/
@Bean
public MongoTemplate getMongoTemplate() {
return new MongoTemplate(getSimpleMongoDbFactory());
}
/**
* 如果有用户名和密码也可以通过MongoClient其他构造函数传参
*
* @return
*/
public SimpleMongoDbFactory getSimpleMongoDbFactory() {
return new SimpleMongoDbFactory(new MongoClient(host, port), dbname);
}
}
APP评论信息表:ap_comment
Field |
Type |
Comment |
id |
int(11) unsigned NOT NULL |
主键 |
author_id |
int(11) unsigned NULL |
用户ID |
author_name |
varchar(20) NULL |
用户昵称 |
entry_id |
bigint(20) unsigned NULL |
|
channel_id |
int(11) unsigned NULL |
频道ID |
type |
tinyint(1) unsigned NULL |
评论内容类型 0 文章 1 动态 |
content |
varchar(255) NULL |
评论内容 |
image |
varchar(50) NULL |
|
likes |
int(5) unsigned NULL |
点赞数 |
reply |
int(5) unsigned NULL |
回复数 |
flag |
tinyint(2) unsigned NULL |
文章标记 0 普通评论 1 热点评论 2 推荐评论 3 置顶评论 4 精品评论 5 大V 评论 |
longitude |
decimal(5,5) NULL |
经度 |
latitude |
decimal(5,5) NULL |
维度 |
address |
varchar(20) NULL |
地理位置 |
ord |
int(11) unsigned NULL |
评论排列序号 |
created_time |
datetime NULL |
创建时间 |
updated_time |
datetime NULL |
更新时间 |
实体类准备:
实体类准备,添加注解@Document与mongodb中的集合对应上;
位置:实体类在pojos包中
内容的逻辑:
- 属性与表的字段名对应,一般是private类型,方法为public类型,对于数据库自动生成的ID字段对应的属性的set方法为private;
- 使用@Data生成set、get方法;
- 在一个只有属性的类上方添加 @Data注解之后,Lombok这玩意会自动帮你生成:
- set()、get()、equals()、hashCode()、toString()
- 使用@Document("ap_comment")
- @Document:
- 标注在实体类上,类似于hibernate的entity注解,标明由mongo来维护该表。
- @Field:属性
- 代表一个字段
- 加这个注解,就是以注解的值对应mongo的key
- 不加这个注解,默认以参数对应mongo的key
内容:
package com.itheima.mongo.pojo;
/**
* APP评论信息
*/
@Data
@Document("ap_comment")
public class ApComment {
/**
* id
*/
private String id;
/**
* 用户ID
*/
private Integer authorId;
/**
* 用户昵称
*/
private String authorName;
/**
* 文章id或动态id
*/
private Long entryId;
/**
* 频道ID
*/
private Integer channelId;
/**
* 评论内容类型
* 0 文章
* 1 动态
*/
private Short type;
/**
* 评论内容
*/
private String content;
/**
* 作者头像
*/
private String image;
/**
* 点赞数
*/
private Integer likes;
/**
* 回复数
*/
private Integer reply;
/**
* 文章标记
* 0 普通评论
* 1 热点评论
* 2 推荐评论
* 3 置顶评论
* 4 精品评论
* 5 大V 评论
*/
private Short flag;
/**
* 经度
*/
private BigDecimal longitude;
/**
* 维度
*/
private BigDecimal latitude;
/**
* 地理位置
*/
private String address;
/**
* 评论排列序号
*/
private Integer ord;
/**
* 创建时间
*/
private Date createdTime;
/**
* 更新时间
*/
private Date updatedTime;
}
基本增删改查:
创建测试类:
位置:
内容:
package com.itheima.mongo.test;
@SpringBootTest(classes = MongoApplication.class)
@RunWith(SpringRunner.class)
public class MongoTest {
@Autowired
private MongoTemplate mongoTemplate;
// 添加 + 修改
@Test
public void testCreate() {
for (int i = 0; i < 10; i++) {
ApComment apComment = new ApComment();
apComment.setContent("这是一个评论");
apComment.setLikes(20 + i);
mongoTemplate.insert(apComment);
}
}
//保存
@Test
public void saveTest() {
for (int i = 0; i < 20; i++) {
ApComment apComment = new ApComment();
apComment.setAuthorName("小王");
apComment.setContent("上海是不错的城市");
apComment.setLikes(i);
mongoTemplate.save(apComment);
}
}
//查询一个
@Test
public void saveFindOne() {
ApComment apComment = mongoTemplate.findById("61e13a76f25a9840f80e1277", ApComment.class);
apComment.setLikes(55);
mongoTemplate.save(apComment);
System.out.println(apComment);
}
//条件查询
@Test
public void testQuery() {
// 查询小于25的值
Query query = Query.query(Criteria.where("likes").lt(28));
// 倒序
query.with(Sort.by(Sort.Direction.DESC, "likes"));
// 分页查询
Pageable pageable = PageRequest.of(1, 3);
query.with(pageable);
List<ApComment> apComments = mongoTemplate.find(query, ApComment.class);
System.out.println(apComments);
}
// 删除
@Test
public void testDel() {
mongoTemplate.remove(Query.query(Criteria.where("_id").is("61e13a76f25a9840f80e1277")), ApComment.class);
}
// 修改
@Test
public void testUpdate() {
Query query = Query.query(Criteria.where("_id").is("61e13e48f25a984adc9c733c"));
Update update = new Update().set("content", "itcast");
mongoTemplate.updateMulti(query, update, ApComment.class);
}
}
结果:
添加成功:
查询一个: