springboot继承组件_springboot2.X 使用spring-data组件对MongoDB做CURD

springboot2.X 使用spring-data组件对MongoDB做CURD

使用背景

基于快速开发,需求不稳定的情况, 我决定使用MongoDB作为存储数据库,搭配使用spring-data

因为快速开发,使用spring data可以直接在类上建表等其他操作,而且对于复合数据模型,MongoDB可以直接存储

代码地址

入门普通级别

1.引入maven依赖

joda-time

joda-time

org.springframework.boot

spring-boot-starter-data-mongodb

cn.hutool

hutool-all

org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-starter-aop

org.springframework.boot

spring-boot-starter-test

test

org.springframework.boot

spring-boot-starter-web

org.projectlombok

lombok

com.alibaba

fastjson

com.google.guava

guava

基于maven dependencyManagement 版本控制如下:

org.springframework.boot

spring-boot-dependencies

2.1.2.RELEASE

pom

import

mysql

mysql-connector-java

5.1.48

cn.hutool

hutool-all

4.5.16

org.mybatis.spring.boot

mybatis-spring-boot-starter

2.0.0

com.alibaba

fastjson

1.2.56

com.alibaba

druid-spring-boot-starter

1.1.9

com.google.guava

guava

19.0

2.使用docker启动MongoDB

docker run --restart="always" \

-d \

--name mongo\

-p 27017:27017\

-v /docker/mongo/data/db:/data/db\

mongo:latest --storageEngine wiredTiger

3.创建Mongo的实体类

@Document(collection="female")

设置id: @Id

设置属性

构建索引

getter/setter

@Document(collection = "female")

@Data

public class Female {

/**

* 主键

*/

@Id

private String id;

/**

* 姓名

*/

private String name;

/**

* 年龄

*/

private String age;

/**

* 哪种类型的女人;FemaleTypeEnums

*/

private Integer type;

/**

* 舔狗

*/

private List dogs;

/**

* 男朋友们

*/

@Indexed

private List boyFriends;

/**

* 男神们

*/

@Indexed

private List dreamers;

/**

* 创建时间

*/

@Indexed

private Date createTime;

/**

* 修改时间

*/

private Date modifiedTime;

}

4.创建Dao层

创建Repository 继承于MongoRepository

根据规则来编写接口方法, spring data mongodb的dao 方法规则详细查看点这里,理论上用idea会提示出来的.

编写单元测试方法

创建Repository 继承于MongoRepository,编写接口方法

public interface FemaleRepository extends MongoRepository {

Page findAllByCreateTimeBetweenAndNameContaining(Date createTime, Date createTime2, String name, Pageable pageable);

Page findAllByCreateTimeBefore(Date createTime, Pageable pageable);

Page findAllByCreateTimeAfter(Date createTime, Pageable pageable);

Page findAllByCreateTimeBetween(Date start, Date end, PageRequest pageRequest);

}

单元测试方法

/**

* description: 添加测试数据

* author: suwenguang

* date: 2019-09-01

*/

@Test

public void addTestData() {

for (int i = 0; i < 1000; i++) {

Female entity = new Female();

entity.setName(RandomUtil.randomString(12));

LocalDate now = LocalDate.now();

LocalDate localDate = now.minusDays(RandomUtil.randomInt(4));

entity.setCreateTime(localDate.toDate());

femaleRepository.save(entity);

}

}

/**

* description: 测试查询构造器

* author: suwenguang

* date: 2019-09-01

*/

public void matching(){

//精确匹配和模糊匹配

Female probe = new Female();

ExampleMatcher matching = ExampleMatcher.matching()

.withMatcher("name", ExampleMatcher.GenericPropertyMatcher.of(ExampleMatcher.StringMatcher.CONTAINING))//模糊匹配

.withIgnorePaths("id")//忽略匹配id

;

PageRequest of = PageRequest.of(0, 10);

Page all = femaleRepository.findAll(Example.of(probe, matching), of);

System.out.println(JSON.toJSONString(all));

}

/**

* description: 测试范围查询

* author: suwenguang

* date: 2019-09-01

*/

@Test

public void findAllByCreateTimeAfter() {

LocalDate yesteday = new LocalDate().minusDays(3);

PageRequest of = PageRequest.of(0, 10);

List byCreateTimeAfter = femaleRepository.findAllByCreateTimeAfter(yesteday.toDate(), of);

System.out.println(JSON.toJSONString(byCreateTimeAfter));

}

/**

* description: 测试范围查询

* author: suwenguang

* date: 2019-09-01

*/

@Test

public void findByCreateTimeBetween() {

LocalDate localDate = new LocalDate();

Page byCreateTimeBetween = femaleRepository.findByCreateTimeBetween(localDate.minusDays(2).toDate(), localDate.toDate(), PageRequest.of(0, 10));

System.out.println(JSON.toJSONString(byCreateTimeBetween.getContent()));

}

进阶Querydsl扩展复杂查询

(基于单表的复杂查询,多表复杂查询暂时不纳入讨论范围)

如果按照以上的用法,动态扩展多条件查询仍然不能够完美支持,会导致代码冗余,当然你如果使用mongoTemlate进行自己封装,另当别论.

那么为了实现动态扩展多条件查询,我去查看对应版本的官方文档,跳转点这里,看到可以集成querydsl作为扩展.

步骤

整合querydsl

使用dsl

1.整合querydsl

pom.xml配置引入依赖

com.querydsl

querydsl-apt

${querydsl.version}

provided

com.querydsl

querydsl-jpa

${querydsl.version}

为什么要注释掉slf4j?

因为我的springboot项目已经引入了slf4j,没必要重复声明,自己可以通过idea的maven dependence查看是否有引入,没有则需要重新引入

2.使用dsl

在dao的repository中继承QuerydslPredicateExecutor

public interface FemaleRepository extends MongoRepository, QuerydslPredicateExecutor {

}

/**

* description: 多条件

* author: suwenguang

* date: 2019-09-01

*/

@Test

public void querydsl() {

PageRequest of = PageRequest.of(0, 10);

QFemale female = QFemale.female;

BooleanExpression createTimeBetween = female.createTime.between(LocalDate.now().minusDays(2).toDate(), LocalDate.now().minusDays(1).toDate());

BooleanBuilder builder = new BooleanBuilder(createTimeBetween);

BooleanExpression contains = female.name.contains("3");

builder.and(contains);

Page all = femaleRepository.findAll(builder,of);

System.out.println(all.getTotalElements());

System.out.println(JSON.toJSONString(all.getContent()));

}

如上所示, 这样子可以动态构造所需要的条件,多个范围查询也可以支持了!!!那么对于后台的搜索数据只需要一个接口就可以了

至于怎么实现,后面再继续整合 X-admin 2.2这个后端模板, 另外出一篇文章吧.

如果对上诉代码有问题或者有其他的扩展性问题,欢迎留下你的评论.

补充

BooleanBuilder的类图, 可以通过idea查看,因为findAll是通过父类继承下来的接口, 里面的Predicate也是一个接口,而BooleanExpression和BooleanBuilder都是实现了Predicate的;

关于找一找教程网

本站文章仅代表作者观点,不代表本站立场,所有文章非营利性免费分享。

本站提供了软件编程、网站开发技术、服务器运维、人工智能等等IT技术文章,希望广大程序员努力学习,让我们用科技改变世界。

[springboot2.X 使用spring-data组件对MongoDB做CURD]http://www.zyiz.net/tech/detail-90135.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值