1 MongoDB
MongoDB是一个基于分布式文件存储的 非关系型 数据库
1.1 应用场景
适用于:
- 高并发的读写操作
- 缓存处理
- 大数据量的存储
不适合于:
- 高度事务性的系统,如银行或会计系统,传统的BI商业智能应用,因为不支持多表的连接查询
1.2 Linux安装mongodb
docker安装
docker pull mongo:latest
docker run -d --restart=always -p 27017:27017 --name mymongo -v /data/db:/data/db-d mongo
** **
docker exec -it mymongo /bin/bash
mongo
> show dbs
常用操作
> db.User.save({name:'zhangsan',age:21,sex:true})
> db.User.find()
2 SpringBoot 集成 mongodb
spring-data-mongodb提供了MongoTemplate 与MongoRepository 两种方式访问mongodb, MongoRepository操作简单,MongoTemplate操作灵活,我们在项目中可以灵活适用这两种方式操作mongodb, MongoRepository的缺点是不够灵活,MongoTemplate正好可以弥补不足。
2.1 java api 基于MongoTemplate 的 CRUD
准备
- 引入依赖
<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>
</dependency>
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
- 配置momgodb地址
spring.data.mongodb.uri=mongodb://192.168.64.128:27017/test
- 创建对应实体类
@Data
@Document("User")
public class User {
@Id
private String id;
private String name;
private Integer age;
private String email;
private String createDate;
}
2.1.1 添加操作
@Test
public void addmongo(){
User user = new User();
user.setAge(20);
user.setName("test");
user.setEmail("123@qq.com");
User user1 = mongoTemplate.insert(user);
System.out.println(user1);
}
2.1.2 查询所有记录
@Test
public void finAll(){
List<User> all = mongoTemplate.findAll(User.class);
System.out.println(all);
}
2.1.3 根据id查询
@Test
public void getById(){
User user = mongoTemplate.findById("6275d057cb081c7207330030", User.class);
System.out.println(user);
}
2.1.4 条件查询
@Test
public void findUserList(){
Query query = new Query(Criteria.where("name").is("test")
.and("age").is(20));
List<User> userList = mongoTemplate.find(query, User.class);
System.out.println(userList);
}
2.1.5 模糊查询
@Test
public void findUserLikeName(){
String name="est";
String regex=String.format("%s%s%s", "^.*",name,".*$");
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
Query query = new Query(Criteria.where("name").regex(pattern));
List<User> users = mongoTemplate.find(query, User.class);
System.out.println(users);
}
2.1.6 分页查询
@Test
public void findUserPage(){
int pageNo=1;
int pageSize=10;
Query query = new Query();
String name="est";
String regex=String.format("%s%s%s", "^.*",name,".*$");
Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
query.addCriteria(Criteria.where("name").regex(pattern));
int totalCount = (int)mongoTemplate.count(query, User.class);
List<User> userList = mongoTemplate.find(
query.skip((pageNo - 1) * pageSize).limit(pageSize), User.class);
HashMap<String, Object> pageMap = new HashMap<>();
pageMap.put("list", userList);
pageMap.put("totalCount", totalCount);
System.out.println(pageMap);
}
2.1.7 修改
@Test
public void updateUser(){
User user = mongoTemplate.findById("6275d6d245f4b158d96ad9a0", User.class);
user.setName("test_1");
user.setAge(25);
user.setEmail("213122@qq.com");
Query query = new Query(Criteria.where("_id").is(user.getId()));
Update update = new Update();
update.set("name", user.getName());
update.set("age", user.getAge());
update.set("email", user.getEmail());
UpdateResult result = mongoTemplate.upsert(query, update, User.class);
long count = result.getModifiedCount();
System.out.println(count);
}
2.1.8 删除
@Test
public void delete(){
Query query = new Query(Criteria.where("_id").is("6275d6d245f4b158d96ad9a0"));
DeleteResult result = mongoTemplate.remove(query, User.class);
long count = result.getDeletedCount();
System.out.println(count);
}
2.2 java api 基于MongoRepository 的 CRUD
Spring Data提供了对mongodb数据访问的支持,我们只需要继承MongoRepository类,按照Spring Data规范就可以了
创建UserRepository 继承 MongoRepository
public interface UserRepository extends MongoRepository<User,String> {
}
注入
@Autowired
private UserRepository userRepository;
2.2.1 添加
@Test
public void addmongo(){
User user = new User();
user.setAge(30);
user.setName("mary");
user.setEmail("12312@qq.com");
User save = userRepository.save(user);
System.out.println(save);
}
2.2.2 查询所有记录
@Test
public void finAll(){
List<User> all = userRepository.findAll();
System.out.println(all);
}
2.2.3 根据 id 查询
@Test
public void getById(){
User user = userRepository.findById("62761fd3c90384674e9edf07").get();
System.out.println(user);
}
2.2.4 条件查询
@Test
public void findUserList(){
User user = new User();
user.setAge(30);
user.setName("mary");
Example<User> userExample=Example.of(user);
List<User> all = userRepository.findAll(userExample);
System.out.println(all);
}
2.2.5 模糊查询
@Test
public void findUserLikeName(){
ExampleMatcher matcher = ExampleMatcher.matching()
.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
.withIgnoreCase(true);
User user = new User();
user.setAge(30);
user.setName("m");
Example<User> userExample=Example.of(user,matcher);
List<User> all = userRepository.findAll(userExample);
System.out.println(all);
}
2.2.6 分页查询
@Test
public void findUserPage(){
PageRequest pageable = PageRequest.of(0, 3);
User user = new User();
user.setName("mary");
Example<User> userExample=Example.of(user);
Page<User> page = userRepository.findAll(userExample, pageable);
System.out.println(page);
}
返回的是一个对象
2.2.7 修改
@Test
public void updateUser(){
User user = userRepository.findById("62761fd3c90384674e9edf07").get();
user.setAge(70);
user.setName("tony");
user.setEmail("asq1212@163.com");
User save = userRepository.save(user);
System.out.println(save);
}
2.2.8 删除
@Test
public void delete(){
userRepository.deleteById("6275d057cb081c7207330030");
}
|