Java操作非关系型数据库mongodb
业务应用场景
传统的关系型数据库(如MySQL),在数据操作的“三高”需求以及应对Web2.0的网站需求面前,显得力不从心。
解释:“三高”需求:
- High performance - 对数据库高并发读写的需求。
- Huge Storage - 对海量数据的高效率存储和访问的需求。
- High Scalability && High Availability- 对数据库的高可扩展性和高可用性的需求。
而MongoDB可应对“三高”需求。
具体的应用场景如:
- 社交场景,使用 MongoDB 存储存储用户信息,以及用户发表的朋友圈信息,通过地理位置索引实现附近的人、地点等功能。
- 游戏场景,使用 MongoDB 存储游戏用户信息,用户的装备、积分等直接以内嵌文档的形式存储,方便查询、高效率存储和访问。
- 物流场景,使用 MongoDB 存储订单信息,订单状态在运送过程中会不断更新,以 MongoDB 内嵌数组的形式来存储,一次查询就能将订单所有的变更读取出来。
- 物联网场景,使用 MongoDB 存储所有接入的智能设备信息,以及设备汇报的日志信息,并对这些信息进行多维度的分析。
- 视频直播,使用 MongoDB 存储用户信息、点赞互动信息等。
这些应用场景中,数据操作方面的共同特点是:
- 数据量大
- 写入操作频繁(读写都很频繁)
- 价值较低的数据,对事务性要求不高
对于这样的数据,我们更适合使用MongoDB来实现数据的存储。
Mongodb的安装
Mongodb简介
MongoDB是一个开源、高性能、无模式的文档型数据库,当初的设计就是用于简化开发和方便扩展,是NoSQL数据库产品中的一种。是最
像关系型数据库(MySQL)的非关系型数据库。
它支持的数据结构非常松散,是一种类似于 JSON 的 格式叫BSON,所以它既可以存储比较复杂的数据类型,又相当的灵活。
MongoDB中的记录是一个文档,它是一个由字段和值对(field:value)组成的数据结构。MongoDB文档类似于JSON对象,即一个文档认
为就是一个对象。字段的数据类型是字符型,它的值除了使用基本的一些类型外,还可以包括其他文档、普通数组和文档数组。
与Mysql的对比
数据类型
Mongodb的单机部署
Windows系统中的安装启动
第一步:下载安装包
MongoDB 提供了可用于 32 位和 64 位系统的预编译二进制包,你可以从MongoDB官网下载安装,MongoDB 预编译二进制包下载地址:
Mongodb下载地址
MongoDB的版本命名规范如:x.y.z;
y为奇数时表示当前版本为开发版,如:1.5.2、4.1.13;
y为偶数时表示当前版本为稳定版,如:1.6.3、4.0.10;
z是修正版本号,数字越大越好。
第二步:解压安装启动
将压缩包解压到一个目录中。
在解压目录中,手动建立一个目录用于存放数据文件,如 data/db
第三步启动Mongodb服务
启动成功图片如下:
cmd连接Mongodb服务
查看是否连接成功
在Mongodb中插入数据测试
db.comment.insertMany([
{
"_id": "1",
"articleid": "100001",
"content": "我们不应该把清晨浪费在手机上,健康很重要,一杯温水幸福你我他。",
"userid": "1002",
"nickname": "相忘于江湖",
"createdatetime": ISODate("2019-08-05T22:08:15.522Z"),
"likenum": NumberInt(1000),
"state": "1"
},
{
"_id": "2",
"content": "我夏天空腹喝凉开水,冬天喝温开水",
"userid": "1005",
"nickname": "伊人憔悴",
"createdatetime": ISODate("2019-08-05T23:58:51.485Z"),
"likenum": NumberInt(888),
{
"_id": "3",
"content": "我一直喝凉开水,冬天夏天都喝。",
"userid": "1004",
"nickname": "杰克船长",
"createdatetime": ISODate("2019-08-06T01:05:06.321Z"),
"likenum": NumberInt(666),
{
"_id": "4",
"content": "专家说不能空腹吃饭,影响健康。",
"userid": "1003",
"nickname": "凯撒",
"createdatetime": ISODate("2019-08-06T08:18:35.288Z"),
"likenum": NumberInt(2000),
{
"_id": "5",
"content": "研究表明,刚烧开的水千万不能喝,因为烫嘴。",
"createdatetime": ISODate("2019-08-06T11:01:02.521Z"),
"likenum": NumberInt(3000),
"state": "1"
}
]);
在这里插入代码片
可以使用compass图形界面连接Mongodb
compass下载链接 解压即用
Java操作Mongodb
目录结构
pom文件内容
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xiaoli</groupId>
<artifactId>mongodbTest</artifactId>
<version>0.0.1-SNAPSHOT</version>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.6.13</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.xiaoli.MongodbTestApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
配置文件application.yml
spring:
#数据源配置
data:
mongodb:
# 主机地址
host: 127.0.0.1
# 数据库
database: articledb
# 默认端口是27017
port: 27017
#也可以使用uri连接
Java中对应的实体类
//把一个java类声明为mongodb的文档,可以通过collection参数指定这个类对应的文档。
//@Document(collection="mongodb 对应 collection 名")
// 若未加 @Document ,该 bean save 到 mongo 的 comment collection
// 若添加 @Document ,则 save 到 comment collection
@Document(collection="comment")//可以省略,如果省略,则默认使用类名小写映射集合
//复合索引
// @CompoundIndex( def = "{'userid': 1,'nickname': -1}")
@Data
@ToString
public class Comment implements Serializable {
//主键标识,该属性的值会自动对应mongodb的主键字段"_id",如果该属性名就叫“id”,则该注解可以省略,否则必须写
@Id
private String id;//主键
//该属性对应mongodb的字段的名字,如果一致,则无需该注解
@Field("content")
private String content;//吐槽内容
private Date publishtime;//发布日期
//添加了一个单字段的索引
@Indexed
private String userid;//发布人ID
private String nickname;//昵称
private LocalDateTime createdatetime;//评论的日期时间
private Integer likenum;//点赞数
private Integer replynum;//回复数
private String state;//状态
private String parentid;//上级ID
private String articleid;
}
dao层
public interface CommentRepository extends MongoRepository<Comment, String> {
//根据父id,查询子评论的分页列表
Page<Comment> findByParentid(String parentid, Pageable pageable);
}
service层
public interface CommentService {
/**
* 保存一个评论
*
* @param comment
*/
public void saveComment(Comment comment);
/**
* 更新评论
*
* @param comment
*/
public void updateComment(Comment comment);
/**
* 根据id删除评论
*
* @param id
*/
public void deleteCommentById(String id);
/**
* 查询所有评论
*
* @return
*/
public List<Comment> findCommentList();
/**
* 根据id查询评论
*
* @param id
* @return
*/
public Comment findCommentById(String id);
/**
* 根据父id查询分页列表
*
* @param parentid
* @param page
* @param size
* @return
*/
public Page<Comment> findCommentListPageByParentid(String parentid, int page, int size);
/**
* 点赞数+1
*
* @param id
*/
public void updateCommentLikenum(String id);
}
service实现类
@Service
public class CommentServiceImpl implements CommentService {
//注入dao
@Autowired
private CommentRepository commentRepository;
//注入MongoTemplate
@Autowired
private MongoTemplate mongoTemplate;
/**
* 点赞数+1
*
* @param id
*/
public void updateCommentLikenum(String id) {
//查询对象
Query query = Query.query(Criteria.where("_id").is(id));
//更新对象
Update update = new Update();
//局部更新,相当于$set
// update.set(key,value)
//递增$inc
// update.inc("likenum",1);
update.inc("likenum");
//参数1:查询对象
//参数2:更新对象
//参数3:集合的名字或实体类的类型Comment.class
mongoTemplate.updateFirst(query, update, "comment");
}
/**
* 保存一个评论
*
* @param comment
*/
public void saveComment(Comment comment) {
//如果需要自定义主键,可以在这里指定主键;如果不指定主键,MongoDB会自动生成主键
//设置一些默认初始值。。。
//调用dao
commentRepository.save(comment);
}
/**
* 更新评论
*
* @param comment
*/
public void updateComment(Comment comment) {
//调用dao
commentRepository.save(comment);
}
/**
* 根据id删除评论
*
* @param id
*/
public void deleteCommentById(String id) {
//调用dao
commentRepository.deleteById(id);
}
/**
* 查询所有评论
*
* @return
*/
public List<Comment> findCommentList() {
//调用dao
return commentRepository.findAll();
}
/**
* 根据id查询评论
*
* @param id
* @return
*/
public Comment findCommentById(String id) {
//调用dao
return commentRepository.findById(id).get();
}
/**
* 根据父id查询分页列表
*
* @param parentid
* @param page
* @param size
* @return
*/
public Page<Comment> findCommentListPageByParentid(String parentid, int size) {
return commentRepository.findByParentid(parentid, PageRequest.of(page - 1, size));
}
}
启动类
@SpringBootApplication
public class ArticleApplication {
public static void main(String[] args) {
SpringApplication.run(ArticleApplication.class, args);
}
}
测试接口
@SpringBootTest
public class CommentServiceTest {
@Autowired
private CommentService commentService;
@Test
public void testFindCommentList() {
List<Comment> commentList = commentService.findCommentList();
System.out.println(commentList);
}
@Test
public void testFindCommentById() {
Comment commentById = commentService.findCommentById("1");
System.out.println(commentById);
}
/**
* 保存一个评论
*/
@Test
public void testSaveComment() {
Comment comment = new Comment();
comment.setArticleid("100000");
comment.setContent("测试添加的数据");
comment.setCreatedatetime(LocalDateTime.now());
comment.setUserid("1003");
comment.setNickname("凯撒大帝");
comment.setState("1");
comment.setLikenum(0);
comment.setReplynum(0);
commentService.saveComment(comment);
}
/**
* 测试根据父id查询子评论的分页列表
*/
@Test
public void testFindCommentListPageByParentid() {
Page<Comment> pageResponse = commentService.findCommentListPageByParentid("3", 1, 2);
System.out.println("----总记录数:" + pageResponse.getTotalElements());
System.out.println("----当前页数据:" + pageResponse.getContent());
}
/**
* 点赞数+1
*/
@Test
public void testUpdateCommentLikenum() {
//对3号文档的点赞数+1
commentService.updateCommentLikenum("3");
}
}
原文地址:https://blog.csdn.net/weixin_45829562/article/details/135254268
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。