摘要: 開始前,建議你們去了解如下文章,固然不看也沒問題: MongoDB從入門到「精通」之簡介和如何安裝 MongoDB從入門到「精通」之如何優雅的安裝 MongoDB從入門到「精通」之整合JavaWeb項目 開發環境 JDK1.java
開始前,建議你們去了解如下文章,固然不看也沒問題:git
MongoDB從入門到「精通」之如何優雅的安裝spring
MongoDB從入門到「精通」之整合JavaWeb項目mongodb
JDK1.七、Maven、Eclipse、SpringBoot1.5.二、mongodb3.4,Robomongo(可視化工具)數據庫
pom.xml:apache
<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 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.itstyle.mongodb</groupId> <artifactId>spring-boot-mongodb</artifactId> <packaging>jar</packaging> <version>0.0.1-SNAPSHOT</version> <name>spring-boot-mongodb</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <java.version>1.7</java.version> </properties> <!-- spring-boot-starter-parent包含了大量配置好的依賴管理,在本身項目添加這些依賴的時候不須要寫<version>版本號 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.2.RELEASE</version> <relativePath/> </parent> <!-- 配置依賴 --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <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> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> </dependencies> <build> <plugins> <!-- 打包項目 mvn clean package --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <dependencies> <!-- mvn spring-boot:run 熱部署啓動 --> <dependency> <groupId>org.springframework</groupId> <artifactId>springloaded</artifactId> <version>1.4.0.RELEASE</version> </dependency> </dependencies> </plugin> </plugins> </build> </project>
實體類 Users.java:數組
package com.itstyle.mongodb.model; import java.io.Serializable; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.index.CompoundIndex; import org.springframework.data.mongodb.core.index.CompoundIndexes; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection="users") @CompoundIndexes({ @CompoundIndex(name = "age_idx", def = "{'name': 1, 'age': -1}") }) public class Users implements Serializable{ private static final long serialVersionUID = 1L; @Indexed private String uid; private String name; private int age; @Transient private String address; public Users(String uid, String name, int age) { super(); this.uid = uid; this.name = name; this.age = age; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return String.format( "Customer[name='%s', age='%s']", name, age); } }
業務接口 IUserService.java:tomcat
package com.itstyle.mongodb.service; import java.util.List; import com.itstyle.mongodb.model.Users; /** * mongodb 案例 * 建立者 小柒 * 建立時間 2017年7月19日 * */ public interface IUserService { public void saveUser(Users users); public Users findUserByName(String name); public void removeUser(String name); public void updateUser(String name, String key, String value); public List<Users> listUser(); }
業務實現UserServiceImpl.java:服務器
package com.itstyle.mongodb.service.impl;
import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.mongodb.core.MongoOperations; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Component; import com.itstyle.mongodb.model.Users; import com.itstyle.mongodb.service.IUserService; @Component("userService") public class UserServiceImpl implements IUserService { @Autowired MongoOperations mongoTemplate; public void saveUser(Users users) { mongoTemplate.save(users); } public Users findUserByName(String name) { return mongoTemplate.findOne( new Query(Criteria.where("name").is(name)), Users.class); } public void removeUser(String name) { mongoTemplate.remove(new Query(Criteria.where("name").is(name)), Users.class); } public void updateUser(String name, String key, String value) { mongoTemplate.updateFirst(new Query(Criteria.where("name").is(name)), Update.update(key, value), Users.class); } public List<Users> listUser() { return mongoTemplate.findAll(Users.class); } }
啓動類Application.java:
package com.itstyle.mongodb; import org.apache.log4j.Logger; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; @EnableAutoConfiguration @ComponentScan(basePackages={"com.itstyle.mongodb"}) public class Application { private static final Logger logger = Logger.getLogger(Application.class); public static void main(String[] args) throws InterruptedException { SpringApplication.run(Application.class, args); logger.info("項目啓動 "); } }
基礎配置application.properties:
# 項目contextPath,通常在正式發佈版本中 server.context-path=/mongodb # 服務端口 server.port=8080 # session最大超時時間(分鐘),默認爲30 server.session-timeout=60 # 該服務綁定IP地址,啓動服務器時如本機不是該IP地址則拋出異常啓動失敗,只有特殊需求的狀況下才配置 # server.address=192.168.16.11 # tomcat最大線程數,默認爲200 server.tomcat.max-threads=800 # tomcat的URI編碼 server.tomcat.uri-encoding=UTF-8 #mongo2.x支持以上兩種配置方式 mongo3.x僅支持uri方式 #mongodb note:mongo3.x will not use host and port,only use uri #spring.data.mongodb.host=192.168.1.180 #spring.data.mongodb.port=27017 #spring.data.mongodb.database=itstyle #沒有設置密碼 #spring.data.mongodb.uri=mongodb://192.168.1.180:27017/itstyle #設置了密碼 spring.data.mongodb.uri=mongodb://itstyle:itstyle@192.168.1.180:27017/itstyle
測試類SpringbootMongodbApplication.java:
package com.itstyle.mongodb.test; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import com.itstyle.mongodb.model.Users; import com.itstyle.mongodb.service.IUserService; @SpringBootApplication @ComponentScan(basePackages={"com.itstyle.mongodb"}) public class SpringbootMongodbApplication implements CommandLineRunner { @Autowired private IUserService userService; public static void main(String[] args) { SpringApplication.run(SpringbootMongodbApplication.class, args); } @Override public void run(String... args) throws Exception { try { Users users = new Users("1", "小明", 10); users.setAddress("青島市"); userService.saveUser(users); List<Users> list = userService.listUser(); System.out.println("一共這麼多人:"+list.size()); } catch (Exception e) { e.printStackTrace(); } } }
最後,運行測試類,使用可視化工具Robomongo查看:
標註在實體類上,與hibernate殊途同歸。
@Document(collection="users") public class Users implements Serializable{ private static final long serialVersionUID = 1L; ...省略代碼
複合索引,加複合索引後經過複合索引字段查詢將大大提升速度。
@Document(collection="users") @CompoundIndexes({ @CompoundIndex(name = "age_idx", def = "{'name': 1, 'age': -1}") }) public class Users implements Serializable{ private static final long serialVersionUID = 1L; ...省略代碼
MongoDB默認會爲每一個document生成一個 _id 屬性,做爲默認主鍵,且默認值爲ObjectId,能夠更改 _id 的值(可爲空字符串),但每一個document必須擁有 _id 屬性。
固然,也能夠本身設置@Id主鍵,不過官方建議使用MongoDB自動生成。
聲明該字段須要加索引,加索引後以該字段爲條件檢索將大大提升速度。
惟一索引的話是@Indexed(unique = true)。
也能夠對數組進行索引,若是被索引的列是數組時,mongodb會索引這個數組中的每個元素。
@Indexed
private String uid;
被該註解標註的,將不會被錄入到數據庫中。只做爲普通的javaBean屬性。
@Transient
private String address;
表明一個字段,能夠不加,不加的話默認以參數名爲列名。
@Field("firstName") private String name;
固然了,以上的以上,可能僅僅是冰山一角,還有不少特性等待你們去挖掘。
代碼:http://git.oschina.net/52itstyle/spring-boot-mongodb
做者: 小柒
出處: https://blog.52itstyle.com
本文版權歸做者和雲棲社區全部,歡迎轉載,但未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出, 若有問題, 可郵件(345849402@qq.com)諮詢。