springboot2整合mongodb4.0.1

springboot2-mongodb-demo

项目介绍
  • springboot2.0.4

  • MongoDB4.0.1数据库

  • 实现了MongoDB的事务

使用说明

1.导入MongoDB的依赖

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

2.配置MongoDB的连接

spring.data.mongodb.uri=mongodb://username:password@localhost:27017/test

3.编写pojo类

当id设置为 ObjectId 类型和添加 @Id 注解时时,MongoDB数据库会自动生成主键,我们在保存对象时就不用设置id的值

package com.zkane.domain;

import lombok.Data;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Id;

/**
 * @author 594781919@qq.com
 * @date 2018/8/12
 */
@Data
public class Employee {
    @Id
    private ObjectId id;
    private String name;
    private Integer age;
}

4.编写dao层的方法

package com.zkane.repository;

import com.zkane.domain.Employee;
import org.springframework.data.mongodb.repository.MongoRepository;

import java.util.List;

/**
 * @author 594781919@qq.com
 * @date 2018/8/12
 */
public interface EmpRepository extends MongoRepository<Employee, Long> {
    Employee findByName(String name);
    List<Employee> findByAgeGreaterThan(int age);
}

jpa支持很多方法命名规则来自动生成查询语句

KeywordSampleLogical result
AfterfindByBirthdateAfter(Date date){“birthdate” : {“$gt” : date}}
GreaterThanfindByAgeGreaterThan(int age){“age” : {“$gt” : age}}
GreaterThanEqualfindByAgeGreaterThanEqual(int age){“age” : {“$gte” : age}}
BeforefindByBirthdateBefore(Date date){“birthdate” : {“$lt” : date}}
LessThanfindByAgeLessThan(int age){“age” : {“$lt” : age}}
LessThanEqualfindByAgeLessThanEqual(int age){“age” : {“$lte” : age}}
BetweenfindByAgeBetween(int from, int to){“age” : {“$gt” : from, “$lt” : to}}
InfindByAgeIn(Collection ages){“age” : {“$in” : [ages…​]}}
NotInfindByAgeNotIn(Collection ages){“age” : {“$nin” : [ages…​]}}
IsNotNull, NotNullfindByFirstnameNotNull(){“firstname” : {“$ne” : null}}
IsNull, NullfindByFirstnameNull(){“firstname” : null}
Like, StartingWith, EndingWithfindByFirstnameLike(String name){“firstname” : name} (name as regex)
NotLike, IsNotLikefindByFirstnameNotLike(String name){“firstname” : { “$not” : name }} (name as regex)
Containing on StringfindByFirstnameContaining(String name){“firstname” : name} (name as regex)
NotContaining on StringfindByFirstnameNotContaining(String name){“firstname” : { “$not” : name}} (name as regex)
Containing on CollectionfindByAddressesContaining(Address address){“addresses” : { “$in” : address}}
NotContaining on CollectionfindByAddressesNotContaining(Address address){“addresses” : { “$not” : { “$in” : address}}}
RegexfindByFirstnameRegex(String firstname){“firstname” : {“$regex” : firstname }}
(No keyword)findByFirstname(String name){“firstname” : name}
NotfindByFirstnameNot(String name){“firstname” : {“$ne” : name}}
NearfindByLocationNear(Point point){“location” : {“$near” : [x,y]}}
NearfindByLocationNear(Point point, Distance max){“location” : {“$near” : [x,y], “$maxDistance” : max}}
NearfindByLocationNear(Point point, Distance min, Distance max){“location” : {“$near” : [x,y], “$minDistance” : min, “$maxDistance” : max}}
WithinfindByLocationWithin(Circle circle){“location” : {“$geoWithin” : {“$center” : [ [x, y], distance]}}}
WithinfindByLocationWithin(Box box){“location” : {“$geoWithin” : {“$box” : [ [x1, y1], x2, y2]}}}
IsTrue, TruefindByActiveIsTrue(){“active” : true}
IsFalse, FalsefindByActiveIsFalse(){“active” : false}
ExistsfindByLocationExists(boolean exists){“location” : {“$exists” : exists }}

5.测试代码

package com.zkane;

import com.zkane.domain.Employee;
import com.zkane.repository.EmpRepository;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class Springboot2MongodbDemoApplicationTests {

    @Autowired
    private EmpRepository empRepository;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Test
    public void test1() {
        Employee employee = new Employee();
        employee.setName("王五");
        employee.setAge(29);
        empRepository.save(employee);
        System.out.println(employee);
    }

    @Test
    public void test2() {
        Employee employee = empRepository.findByName("张三");
        System.out.println(employee);
    }

    @Test
    public void test3() {
                // 通过MongoTemplate来查询数据
        Query query = new Query(Criteria.where("age").in(20, 23));
        List<Employee> employees = mongoTemplate.find(query, Employee.class);
        System.out.println(employees);
    }

    @Test
        public void test4() {
            // 查询年龄大于25的数据
            List<Employee> employeeList = empRepository.findByAgeGreaterThan(25);
            System.out.println(employeeList);
        }

}
MongoDB的事务

1.目前事务回滚只能在复制集上操作,单独的mongodb server不能操作事务

  • 开启服务器27017
D:\Program Files\MongoDB\Server\4.0\bin> .\mongod.exe -dbpath ..\data\db   --replSet rs0
  • 开启服务器27018
D:\Program Files\MongoDB\Server\4.0\bin> .\mongod.exe -dbpath ..\data\db27018 --port 27018  --replSet rs0
  • 设置集群
D:\Program Files\MongoDB\Server\4.0\bin> .\mongo.exe --port 27017
> rs.initiate()
rs0:SECONDARY> rs.add('localhost:27018')

2.代码实现

package com.zkane.service;

import com.alibaba.fastjson.JSONObject;
import com.mongodb.MongoClient;
import com.mongodb.MongoException;
import com.mongodb.client.ClientSession;
import com.mongodb.client.MongoCollection;
import com.zkane.domain.Address;
import com.zkane.domain.Employee;
import com.zkane.repository.EmpRepository;
import org.bson.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

    /**
     * @author: 594781919@qq.com
     * @date: 2018/8/13
     */
    @Service
    public class EmployeeService {

        @Autowired
        private EmpRepository empRepository;

        @Autowired
        private MongoClient client;

        /**
         * 测验MongoDB的事务回滚
         */
        public void save() {
            try (ClientSession clientSession = client.startSession()) {
                clientSession.startTransaction();
                Employee employee = new Employee();
                employee.setName("王五");
                employee.setAge(31);
                Address address = new Address();
                address.setCity("北京");
                address.setStreet("长安路");
                employee.setAddress(address);
                MongoCollection<Document> employeeCollection = client.getDatabase("test").getCollection("employee");
                employeeCollection.insertOne(clientSession, Document.parse(JSONObject.toJSONString(employee)));

                //int i = 1 / 0;

                employee = new Employee();
                employee.setName("赵六");
                employee.setAge(25);
                address = new Address();
                address.setCity("北京");
                address.setStreet("太升路");
                employee.setAddress(address);
                employeeCollection.insertOne(clientSession, Document.parse(JSONObject.toJSONString(employee)));

                commitWithRetry(clientSession);
            }

        }

    /**
     * 提交失败时,进行重新提交
     * @param clientSession
     */
    void commitWithRetry(ClientSession clientSession) {
        while (true) {
            try {
                clientSession.commitTransaction();
                System.out.println("Transaction committed");
                break;
            } catch (MongoException e) {
                // can retry commit
                if (e.hasErrorLabel(MongoException.UNKNOWN_TRANSACTION_COMMIT_RESULT_LABEL)) {
                    System.out.println("UnknownTransactionCommitResult, retrying commit operation ...");
                    continue;
                } else {
                    System.out.println("Exception during commit ...");
                    throw e;
                }
            }
        }
    }
}

源码地址:码云

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值