1.創建工程並引入依賴
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.6.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <dependencies> <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> </dependencies>
2.創建application.yml
spring: #數據源配置 data: mongodb: #主機地址 host: 192.168.43.182 #數據庫 database: articledb #默認端口是27017 port: 27017 #也可以使用uri連接 #uri: mongodb://192.168.43.182:27017/articledb #如果數據庫需要密碼認證 #uri: mongodb://bobo:123456@192.168.43.182:27017/articledb
3.創建啟動類
@SpringBootApplication
public class ArticleApplication {
public static void main(String[] args) {
SpringApplication.run(ArticleApplication.class, args);
}
}
4.啟動項目,看是否能正常啟動,控制台沒有錯誤
5.文章評論實體類的編寫
/** * 文章評論實體類 */ @Document(collection = "comment")// 可以省略,如果省略,則默認使用類名小寫映射集合 // 復合索引 // @CompoundIndex( def = "{'userid': 1, 'nickname': -1}") 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; // 文章id /********************* get/set方法 *********************/ }
說明:
索引可以大大提升查詢效率,一般在查詢字段上添加索引,索引的添加可以通過Mongo的命令來添加,也可以在Java的實體類中通過注解添加。
1)單字段索引注解@Indexed
聲明該字段需要索引,建索引可以大大的提高查詢效率。
Mongo命令參考:db.comment.createIndex({"userid":1})
2 )復合索引注解@CompoundIndex
復合索引的聲明,建復合索引可以有效地提高多字段的查詢效率。
Mongo命令參考:db.comment.createIndex({"userid":1,"nickname":-1})
6.創建數據訪問接口
/** * 評論的持久層接口 */ public interface CommentDao extends MongoRepository<Comment, String> { }
7.創建業務邏輯類
/** * 評論的業務層 */ @Service public class CommentService { @Autowired private CommentDao commentDao; /** * 保存一個評論 * @param comment */ public void saveComment(Comment comment) { //如果需要自定義主鍵,可以在這里指定主鍵;如果不指定主鍵,MongoDB會自動生成主鍵 commentDao.save(comment); } /** * 更新評論 * @param comment */ public void updateComment(Comment comment) { commentDao.save(comment); } /** * 根據id刪除評論 * @param id */ public void deleteCommentById(String id) { commentDao.deleteById(id); } /** * 查詢所有評論 * @return */ public List<Comment> findCommentList() { return commentDao.findAll(); } /** * 根據id查詢評論 * @param id * @return */ public Comment findCommentById(String id) { return commentDao.findById(id).get(); } }
8.測試
@RunWith(SpringRunner.class) @SpringBootTest(classes = ArticleApplication.class) public class CommentServiceTest { @Autowired private CommentService commentService; /** * 保存一個評論 */ @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); } /** * 查詢所有數據 */ @Test public void testFindAll() { List<Comment> list = commentService.findCommentList(); System.out.println(list); } /** * 測試根據id查詢 */ @Test public void testFindCommentById() { Comment comment = commentService.findCommentById("1"); System.out.println(comment); } }
MongoTemplate 實現評論點贊
低效率的點贊代碼: CommentService 新增 updateThumbup方法
/** * 點贊-效率低 * @param id */ public void updateCommentThumbupToIncrementingOld(String id){ Comment comment = commentDao.findById(id).get(); comment.setLikenum(comment.getLikenum() + 1); commentDao.save(comment); }
以上方法雖然實現起來比較簡單,但是執行效率並不高,因為我們只需要將點贊數加 1 就可以了,沒必要查詢出所有字段修改后再更新所有字段。(蝴蝶效應)
可以使用MongoTemplate類來實現對某列的操作。
(1)修改CommentService
//注入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"); mongoTemplate.updateFirst(query, update, Comment.class); }
(2)測試
/** * 點贊數+1 */ @Test public void testUpdateCommentLikenum() { //對3號文檔的點贊數+1 commentService.updateCommentLikenum("3"); }
SpringDataMongoDB 連接副本集
副本集語法:
mongodb://host1,host2,host3/articledb?connect=replicaSet&slaveOk=true&replicaSet=副本集名字
slaveOk=true :開啟副本節點讀的功能,可實現讀寫分離。
connect=replicaSet :自動到副本集中選擇讀寫的主機。如果slaveOK是打開的,則實現了讀寫分離
修改配置文件application.yml:
spring: #數據源配置 data: mongodb: #主機地址 #host: 192.168.43.182 #數據庫 #database: articledb #默認端口是27017 #port: 27017 #副本集的連接字符串 uri: mongodb://192.168.43.182:27017,192.168.43.182:27018,192.168.43.182:27019/articledb?connect=replicaSet&slaveOk=true&replicaSet=myrs
注意:主機必須是副本集中所有的主機,包括主節點、副本節點、仲裁節點。
完整的連接字符串的參考:
MongoDB客戶端連接語法
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
mongodb:// 這是固定的格式,必須要指定。
username:password@ 可選項,如果設置,在連接數據庫服務器之后,驅動都會嘗試登陸這個數據庫
host1 必須的指定至少一個host, host1 是這個URI唯一要填寫的。它指定了要連接服務器的地址。如果要連接副本集,請指定多個主機地址。
portX 可選的指定端口,如果不填,默認為27017
/database 如果指定username:password@,連接並驗證登陸指定數據庫。若不指定,默認打開test 數據庫。
?options 是連接選項。如果不使用/database,則前面需要加上/。所有連接選項都是鍵值對name=value,鍵值對之間通過&或;(分號)隔開
選項(options):
SpringDataMongDB 連接分片集群:
其連接的是mongs路由,配置和單機mongod的配置是一樣的。
多個路由的時候的SpringDataMongoDB的客戶端配置參考如下:
spring: #數據源配置 data: mongodb: #主機地址 #host: 192.168.43.182 #數據庫 #database: articledb #默認端口是27017 #port: 27017 #副本集的連接字符串 #uri: mongodb://192.168.43.182:27017,192.168.43.182:27018,192.168.43.182:27019/articledb?connect=replicaSet&slaveOk=true&replicaSet=myrs #連接路由字符串 uri: mongodb://192.168.43.182:27017,192.168.43.182:27117/articledb