第一步,使用SPRING INITIALIZR https://start.spring.io/ 添加mongodb依赖生成项目
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.20</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
第二步, 然后配置application.yml
mongoDB连接字符串格式为:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
mongodb:// is a required prefix to identify that this is a string in the standard connection format.
username:password@ are optional. If given, the driver will attempt to login to a database after connecting to a database server. For some authentication mechanisms, only the username is specified and the password is not, in which case the ":" after the username is left off as well
host1 is the only required part of the URI. It identifies a server address to connect to.
:portX is optional and defaults to :27017 if not provided.
/database is the name of the database to login to and thus is only relevant if the username:password@ syntax is used. If not specified the "admin" database will be used by default.
?options are connection options. Note that if database is absent there is still a / required between the last host and the ? introducing the options. Options are name=value pairs and the pairs are separated by "&". For backwards compatibility, ";" is accepted as a separator in addition to "&", but should be considered as deprecated.
我的测试环境mongodB采用的是副本集方式,所以mongoDB连接字符串配置为:
spring:
data:
mongodb:
uri: mongodb://app_bill_rw:9240^XB4r82qd@10.139.60.166:27017,10.139.60.167:27017,10.139.60.168:27017/bill?replicaSet=rskkd
这里的options只配置了replicaSet,其他的采用默认的配置,但其实还可以配置serverSelectionTimeoutMS,maxPoolSize,slaveOk等其他选项。
The following options are supported (case insensitive):
Server Selection Configuration:
serverSelectionTimeoutMS=ms: How long the driver will wait for server selection to succeed before throwing an exception.
localThresholdMS=ms: When choosing among multiple MongoDB servers to send a request, the driver will only send that request to a server whose ping time is less than or equal to the server with the fastest ping time plus the local threshold.
Server Monitoring Configuration:
heartbeatFrequencyMS=ms: The frequency that the driver will attempt to determine the current state of each server in the cluster.
Replica set configuration:
replicaSet=name: Implies that the hosts given are a seed list, and the driver will attempt to find all members of the set.
Connection Configuration:
ssl=true|false: Whether to connect using SSL.
sslInvalidHostNameAllowed=true|false: Whether to allow invalid host names for SSL connections.
connectTimeoutMS=ms: How long a connection can take to be opened before timing out.
socketTimeoutMS=ms: How long a send or receive on a socket can take before timing out.
Connection pool configuration:
maxPoolSize=n: The maximum number of connections in the connection pool.
waitQueueMultiple=n : this multiplier, multiplied with the maxPoolSize setting, gives the maximum number of threads that may be waiting for a connection to become available from the pool. All further threads will get an exception right away.
waitQueueTimeoutMS=ms: The maximum wait time in milliseconds that a thread may wait for a connection to become available.
Write concern configuration:
safe=true|false
true: the driver sends a getLastError command after every update to ensure that the update succeeded (see also w and wtimeoutMS).
false: the driver does not send a getLastError command after every update.
journal=true|false
true: the driver waits for the server to group commit to the journal file on disk.
false: the driver does not wait for the server to group commit to the journal file on disk.
w=wValue
The driver adds { w : wValue } to the getLastError command. Implies safe=true.
wValue is typically a number, but can be any string in order to allow for specifications like "majority"
wtimeoutMS=ms
The driver adds { wtimeout : ms } to the getlasterror command. Implies safe=true.
Used in combination with w
Read preference configuration:
slaveOk=true|false: Whether a driver connected to a replica set will send reads to slaves/secondaries.
readPreference=enum: The read preference for this connection. If set, it overrides any slaveOk value.
Enumerated values:
primary
primaryPreferred
secondary
secondaryPreferred
nearest
readPreferenceTags=string. A representation of a tag set as a comma-separated list of colon-separated key-value pairs, e.g. "dc:ny,rack:1". Spaces are stripped from beginning and end of all keys and values. To specify a list of tag sets, using multiple readPreferenceTags, e.g. readPreferenceTags=dc:ny,rack:1;readPreferenceTags=dc:ny;readPreferenceTags=
Note the empty value for the last one, which means match any secondary as a last resort.
Order matters when using multiple readPreferenceTags.
Authentication configuration:
authMechanism=MONGO-CR|GSSAPI|PLAIN|MONGODB-X509: The authentication mechanism to use if a credential was supplied. The default is unspecified, in which case the client will pick the most secure mechanism available based on the sever version. For the GSSAPI and MONGODB-X509 mechanisms, no password is accepted, only the username.
authSource=string: The source of the authentication credentials. This is typically the database that the credentials have been created. The value defaults to the database specified in the path portion of the URI. If the database is specified in neither place, the default value is "admin". This option is only respected when using the MONGO-CR mechanism (the default).
gssapiServiceName=string: This option only applies to the GSSAPI mechanism and is used to alter the service name..
第三步,创建表
import lombok.*;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.math.BigDecimal;
/**
* @Author zhouliliang
* @Description:
* @Date: Created in 2018/7/24 9:47
*/
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
@Document(collection = "between")
public class Between {
@Id
private String id;
private String billMonth;
private BigDecimal amount;
}
第四步,创建查询
package com.mongo.mongo4.repository;
import com.mongo.mongo4.entity.Between;
import org.springframework.data.mongodb.repository.MongoRepository;
/**
* @Author zhouliliang
* @Description:
* @Date: Created in 2018/8/1 10:11
*/
public interface BetweenRepository extends MongoRepository<Between, String> {
}
第五步,指定MongoDB Repository的扫描目录
@SpringBootApplication
@EnableMongoRepositories(basePackages = "com.mongo.mongo4.repository")
public class Mongo4Application {
public static void main(String[] args) {
SpringApplication.run(Mongo4Application.class, args);
}
}
最后测试一下:
@Component
public class MyRunner implements CommandLineRunner {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private BetweenRepository betweenRepository;
@Override
public void run(String... args) {
mongoTemplate.dropCollection(Between.class);
List<Between> betweenList = Arrays.asList(new Between("1", "2018-01", new BigDecimal(12.13)),
new Between("2", "2018-01", new BigDecimal(12.24)),
new Between("3", "2018-02", new BigDecimal(12.35)),
new Between("4", "2018-03", new BigDecimal(12.43)),
new Between("5", "2018-03", new BigDecimal(12.56)));
// mongoTemplate.insert(betweens, Between.class);
betweenRepository.saveAll(betweenList);
betweenRepository.findAll().forEach(System.out::println);
System.out.println("使用mongoTemplate查询");
mongoTemplate.find(new Query(Criteria.where("billMonth").gte("2018-02").lte("2018-03")), Between.class)
.forEach(System.out::println);
}
}