代码拉取完成,页面将自动刷新
同步操作将从 knowz/springboot2-mongodb-demo 强制同步,此操作会覆盖自 Fork 仓库以来所做的任何修改,且无法恢复!!!
确定后同步将在后台操作,完成时将刷新页面,请耐心等待。
springboot2.0.4
MongoDB4.0.1数据库
实现了MongoDB的事务
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
spring.data.mongodb.uri=mongodb://username:password@localhost:27017/test
当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;
}
jpa支持很多方法命名规则来自动生成查询语句
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);
}
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);
}
}
D:\Program Files\MongoDB\Server\4.0\bin> .\mongod.exe -dbpath ..\data\db --replSet rs0
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.代码实现
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
<exclusions>
<exclusion>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
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;
}
}
}
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。