k8s 部署 MongoDB 三种模式:https://blog.csdn.net/weixin_42555971/article/details/126243336

 

开始

pom 配置 文件

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

版本:springboot 2.5.x
配置 application.yml
uri实例:mongodb://root:password@192.168.101.01:30017/database

spring:
  data:
    mongodb:
      uri:  mongodb://[用户名]:[密码]@[ip]:[端口]/[数据库]

版本:springboot 2.7.x
配置 application.yml

spring:
  data:
    mongodb:
      host: 192.168.101.01
      port: 30017
      database: test
      authentication-database: admin
      username: root
      password: password

连接成功

2022-10-10 11:15:30.902  INFO 55948 --- [           main] org.mongodb.driver.client                : MongoClient with metadata {"driver": {"name": "mongo-java-driver|sync|spring-boot", "version": "4.6.1"}, "os": {"type": "Windows", "name": "Windows 11", "architecture": "amd64", "version": "10.0"}, "platform": "Java/Oracle Corporation/11.0.15+8-LTS-149"} created with settings MongoClientSettings{readPreference=primary, writeConcern=WriteConcern{w=null, wTimeout=null ms, journal=null}, retryWrites=true, retryReads=true, readConcern=ReadConcern{level=null}, credential=MongoCredential{mechanism=null, userName='root', source='upms', password=<hidden>, mechanismProperties=<hidden>}, streamFactoryFactory=null, commandListeners=[], codecRegistry=ProvidersCodecRegistry{codecProviders=[ValueCodecProvider{}, BsonValueCodecProvider{}, DBRefCodecProvider{}, DBObjectCodecProvider{}, DocumentCodecProvider{}, IterableCodecProvider{}, MapCodecProvider{}, GeoJsonCodecProvider{}, GridFSFileCodecProvider{}, Jsr310CodecProvider{}, JsonObjectCodecProvider{}, BsonCodecProvider{}, EnumCodecProvider{}, com.mongodb.Jep395RecordCodecProvider@68ef01a5]}, clusterSettings={hosts=[192.168.101.01:30017], srvServiceName=mongodb, mode=SINGLE, requiredClusterType=UNKNOWN, requiredReplicaSetName='null', serverSelector='null', clusterListeners='[]', serverSelectionTimeout='30000 ms', localThreshold='30000 ms'}, socketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=0, receiveBufferSize=0, sendBufferSize=0}, heartbeatSocketSettings=SocketSettings{connectTimeoutMS=10000, readTimeoutMS=10000, receiveBufferSize=0, sendBufferSize=0}, connectionPoolSettings=ConnectionPoolSettings{maxSize=100, minSize=0, maxWaitTimeMS=120000, maxConnectionLifeTimeMS=0, maxConnectionIdleTimeMS=0, maintenanceInitialDelayMS=0, maintenanceFrequencyMS=60000, connectionPoolListeners=[], maxConnecting=2}, serverSettings=ServerSettings{heartbeatFrequencyMS=10000, minHeartbeatFrequencyMS=500, serverListeners='[]', serverMonitorListeners='[]'}, sslSettings=SslSettings{enabled=false, invalidHostNameAllowed=false, context=null}, applicationName='null', compressorList=[], uuidRepresentation=JAVA_LEGACY, serverApi=null, autoEncryptionSettings=null, contextProvider=null}
2022-10-10 11:15:30.910  INFO 55948 --- [68.101.01:30017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:2, serverValue:20109}] to 192.168.101.01:30017
2022-10-10 11:15:30.910  INFO 55948 --- [68.101.01:30017] org.mongodb.driver.connection            : Opened connection [connectionId{localValue:1, serverValue:20108}] to 192.168.101.01:30017
2022-10-10 11:15:30.910  INFO 55948 --- [68.101.01:30017] org.mongodb.driver.cluster               : Monitor thread successfully connected to server with description ServerDescription{address=192.168.101.01:30017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=13, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=8421400}

 

引入

引入使用 MongoRepository

  • TestDO:数据库表实体
  • Long:表 id 类型
@Repository
public interface TestMapper extends MongoRepository<TestDO, Long> {

}

TestPO

@Data
@EqualsAndHashCode
@NoArgsConstructor
@AllArgsConstructor
public class TestPO {

    private Long id;

    private String name;

    private String description;
}

 

增删改查

新增

@PostMapping("/test")
public Result<String> insert() throws Exception {
    TestPO testPO = new TestPO(RandomUtils.nextLong(), "name" + RandomUtils.nextLong(), "description" + RandomUtils.nextLong());
    testMapper.insert(testPO);
    log.info("insert");
    return Result.success("创建成功!", null);
}

修改

@PutMapping("/test")
public Result<String> update(@RequestBody TestPO testPO) throws Exception {
    testMapper.save(testPO);
    log.info("update");
    return Result.success("更新成功!", null);
}

删除

@DeleteMapping("/test/{id}")
public Result<String> delete(@PathVariable Long id) throws Exception {
   testMapper.deleteById(id);
   log.info("delete");
   return Result.success("物理删除成功!", null);
}

列表查询,id 倒序排列

@GetMapping("/test/list")
public Result<List<TestPO>> list() throws Exception {
   Sort sort = Sort.by(Sort.Direction.DESC, "id");
   List<TestPO> list = testMapper.findAll(sort);
   log.info("list");
   return Result.success("列表查询成功!", list);
}

分页查询

@GetMapping("/test/page")
public Result<Page<TestPO>> page(PageQuery query) throws Exception {
   Pageable page = PageRequest.of(query.getPage() - 1, query.getSize(),
           Sort.Direction.DESC, "id");
   Page<TestPO> data = testMapper.findAll(page);
   return Result.success("分页查询成功!", data);
}

分页返回值

content:查询结果
totalElements:数据总条数

{
        "content": [
            {
                "id": 8799847925169867980,
                "name": "name3965386973422561722",
                "description": "description291993708272834881"
            },
            {
                "id": 8320195335381332305,
                "name": "name3486718732517274306",
                "description": "description5901125140142081486"
            },
            {
                "id": 8270452999067863674,
                "name": "name8216957183087162232",
                "description": "description3577532700047157352"
            },
            {
                "id": 8004700415267527277,
                "name": "name6463034386689455436",
                "description": "description8062032918850052067"
            },
            {
                "id": 7647846900891711673,
                "name": "nn2",
                "description": "dd2"
            }
        ],
        "pageable": {
            "sort": {
                "empty": false,
                "sorted": true,
                "unsorted": false
            },
            "offset": 0,
            "pageNumber": 0,
            "pageSize": 5,
            "paged": true,
            "unpaged": false
        },
        "last": false,
        "totalPages": 5,
        "totalElements": 21,
        "size": 5,
        "number": 0,
        "sort": {
            "empty": false,
            "sorted": true,
            "unsorted": false
        },
        "numberOfElements": 5,
        "first": true,
        "empty": false
    }

 

条件查询

StringMatcher 枚举

  • CONTAINING:匹配包含的字符串
  • DEFAULT:默认匹配模式
  • ENGING:匹配结尾的字符串
  • EXACT:精确匹配字符串
  • REGEX:将字符串作为正则表达式匹配
  • STARTING:匹配开头的字符串

等于,name 等于 nn

Sort sort = Sort.by(Sort.Direction.DESC, "id");
TestPO testPO = new TestPO();
testPO.setName("nn");

Example<TestPO> example = Example.of(testPO);
List<TestPO> list = testMapper.findAll(example, sort);

包含 - like,name 包含 nn

TestPO testPO = new TestPO();
testPO.setName("nn");

ExampleMatcher matcher=ExampleMatcher.matching()
        .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
        .withIgnoreCase(true);

Example<TestPO> example = Example.of(testPO, matcher);
List<TestPO> list = testMapper.findAll(example);

多条件查询,name 包含 nn 而且 description 包含 dd

TestPO testPO = new TestPO();
testPO.setName("nn");
testPO.setDescription("dd");

ExampleMatcher matcher = ExampleMatcher.matching()
       .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.contains())
       .withMatcher("description", ExampleMatcher.GenericPropertyMatchers.contains());

Example<TestPO> example = Example.of(testPO, matcher);
List<TestPO> list = testMapper.findAll(example);

条件查询并分页

TestPO testPO = new TestPO();
testPO.setName("nn1");

Pageable page = PageRequest.of(query.getPage() - 1, query.getSize(),
       Sort.Direction.DESC, "id");
Example<TestPO> example = Example.of(testPO);

Page<TestPO> data = testMapper.findAll(example, page);
Logo

K8S/Kubernetes社区为您提供最前沿的新闻资讯和知识内容

更多推荐