原文地址:https://www.cnblogs.com/okong/p/springboot-thirty-one.html
mongodb 的安装
下载地址:https://fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-4.0.3-signed.msi
下载结束后 安装就好
开始集成
加入POM依赖
<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>
创建实体
/**
* 通知消息对象
* @author oKong
*
*/
@Document(collection="notify_msg")//集合名
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class NotifyMsg implements Serializable{
/**
*
*/
private static final long serialVersionUID = -8985545025018238754L;
@Id
String id;
/**
* 消息类型
*/
@Indexed
String notifyType;
/**
* 消息单号
*/
@Indexed
String notifyNo;
/**
* 消息通知日期
*/
String notifyDate;
/**
* 消息体
*/
@Field("notifyMsg")//可指定存储时的字段名
String notifyMsg;
/**
* 创建时间
*/
@CreatedDate
Date gmtCreate;
}
这里注意:@Document(collection=“notify_msg”) 表示:操作的集合为:notify_msg。
这个可手动使用工具创建下。
另外,针对@CreatedDate注解,也和之前的jpa用法一直,创建时会自动赋值,需要在启动类中添加@EnableMongoAuditing注解使其生效!
同时,可使用@Field注解,可指定存储的键值名称,默认就是类字段名。如设置@Field(“notify_Msg”)后,效果如下:
配置文件中填写连接地址
# mongodb
# 单机模式 mongodb://name:pass@ip:port/database
# 集群模式 mongodb://user:pwd@ip1:port1,ip2:port2/database
spring.data.mongodb.uri=mongodb://127.0.0.1:27017/learning
启动类编写
/**
* mongodb 集成示例
* @author oKong
*
*/
@SpringBootApplication
@EnableMongoAuditing
//@EnableMongoRepositories(basePackages="cn.lqdev")//当有些dao不在default page下时 可通过此方法进行注册扫描包
@Slf4j
public class MongodbApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(MongodbApplication.class, args);
log.info("spring-boot-mongodb-chapter31启动!");
}
}
注意:当使用MongoRepositories时,可能有些MongoRepositories类不在默认的包路径(启动类路径)下,可使用@EnableMongoRepositories的basePackages需要扫描的路径信息。若都在默认的包路径下,可以不加此注解的。
MongoTemplate方式
创建一个接口类。
/**
* 接口服务
* @author oKong
*
*/
public interface NotifyMsgService {
/**
* 保存数据
* @author 作者:oKong
*/
NotifyMsg saveNotifyMsg(NotifyMsg msg);
/**
* 根据消息号查找
* @author 作者:oKong
*/
NotifyMsg findNotifyMsgByNo(String notifyNo);
/**
* 根据消息日期查找
* @author 作者:oKong
*/
List<NotifyMsg> findNotifyMsgByDate(String notifyDate);
/**
* 根据id进行删除 返回删除的对象
* @author 作者:oKong
*/
NotifyMsg delNotifyMsgById(String id);
}
接口实现类,引入MongoTemplate。
/**
* MongoTemplate 访问实现
* @author oKong
*
*/
@Service
public class NotifyMsgServiceImpl implements NotifyMsgService{
@Autowired
MongoTemplate mongoTemplate;
@Override
public NotifyMsg saveNotifyMsg(NotifyMsg msg) {
//使用 save和insert都可以进行插入
//区别:当存在"_id"时
//insert 插入已经存在的id时 会异常
//save 则会进行更新
//简单来说 save 就是不存在插入 存在更新
mongoTemplate.insert(msg);
mongoTemplate.save(msg);
return msg;
}
@Override
public NotifyMsg findNotifyMsgByNo(String notifyNo) {
//根据Criteria 改造查询条件
Query query = new Query(Criteria.where("notifyNo").is(notifyNo));
return mongoTemplate.findOne(query, NotifyMsg.class);
}
@Override
public List<NotifyMsg> findNotifyMsgByDate(String notifyDate) {
//查找 notifyDate 根据Criteria 改造查询条件
Query query = new Query(Criteria.where("notifyDate").is(notifyDate));
return mongoTemplate.find(query, NotifyMsg.class);
}
@Override
public NotifyMsg delNotifyMsgById(String id) {
//查找 id 根据Criteria 改造查询条件
Query query = new Query(Criteria.where("id").is(id));
return mongoTemplate.findAndRemove(query, NotifyMsg.class);
}
}
针对查询,可以使用org.springframework.data.mongodb.core.query.Criteria对象进行构造查询条件。其提供的方法如下:
具体使用时,可根据实际情况进行组合查询条件。
针对save和insert也需要注意下:
- 在无_id情况下,两者都能进行新增操作。
- 存在_id,同时记录库里不存在,两者都是进行插入操作。
- 存在_id,同时库里也存在记录,save相当于进行更新操作。而insert直接就异常了。
2.创建示例控制层。
/**
* mongoTemplate 示例
* @author oKong
*
*/
@RestController
@RequestMapping("/template")
@Slf4j
public class MongoTemplateController {
@Autowired
NotifyMsgService notifyMsgService;
@PostMapping("/add")
public NotifyMsg add(NotifyMsg msg) {
log.info("mongoTemplate方式新增:{}", msg);
return notifyMsgService.saveNotifyMsg(msg);
}
@PostMapping("del/{id}")
public NotifyMsg del(@PathVariable String id) {
log.info("mongoTemplate方式删除:{}", id);
return notifyMsgService.delNotifyMsgById(id);
}
@GetMapping("/find/{no}")
public NotifyMsg findNotifyMsgByNo(@PathVariable String no){
log.info("mongoTemplate方式查找:notifyNo-{}", no);
return notifyMsgService.findNotifyMsgByNo(no);
}
@GetMapping("/find/list/{date}")
public List<NotifyMsg> findNotifyMsgByDate(@PathVariable String date){
log.info("mongoTemplate方式查找:notifyDate-{}", date);
return notifyMsgService.findNotifyMsgByDate(date);
}
}
启动应用,使用Postman进行访问。
新增:http://127.0.0.1:8080//template/add
可以看见,已经返回对应的信息,同时数据库也可看见记录了。
其他的都是类似的,大家可自行访问下:
- 根据日期返回列表信息:http://127.0.0.1:8080//template/find/list/具体日期
- 根据ID删除:http://127.0.0.1:8080/template/del/具体ID值
- 根据消息号查询:http://127.0.0.1:8080//template/find/具体消息号
MongoRepository方式
在是jpa的方式进行操作数据,优雅,简单
创建资源类
/**
* MongoRepository 示例
* @author oKong
*
*/
public interface NotifyMsgDao extends MongoRepository<NotifyMsg, String>{
/*
* 根据消息号进行查询
*/
NotifyMsg findByNotifyNo(String notifyNo);
/**
* 根据日期查询 自定义查询
* @author 作者:oKong
*/
//需要注意 查询的语法结构 ,同时这里和`jpa`不一样的地方是,第一个索引值从0 开始。。
@Query("{'notifyDate':?0}")
Page<NotifyMsg> queryBySql(String notifyDate,Pageable pageable);
}
这里需要注意一个地方:和上一章节的自定义sql不同之处是,参数索引值从0开始。
同时,要注意查询的语法。具体用法,可查看:https://docs.spring.io/spring-data/mongodb/docs/1.10.14.RELEASE/reference/html/#mongodb.repositories.queries 这里简单截图下:
1.编写示例控制层。
/**
* MongoRepository 示例
* @author oKong
*
*/
@RestController
@RequestMapping("/repository")
@Slf4j
public class MongoRepositoryController {
@Autowired
NotifyMsgDao notifyMsgDao;
@PostMapping("/add")
public NotifyMsg add(NotifyMsg msg) {
log.info("repository方式新增:{}", msg);
return notifyMsgDao.save(msg);
}
@GetMapping("/find/sql/{date}")
public Page<NotifyMsg> queryBySql(@PathVariable String date){
Pageable pageable = new PageRequest(0, 10);
log.info("repository方式分页sql查找日期:{}", date);
return notifyMsgDao.queryBySql(date, pageable);
}
@GetMapping("/find/{no}")
public NotifyMsg findByNotifyNo(@PathVariable String no) {
log.info("repository方式查找单号:{}", no);
return notifyMsgDao.findByNotifyNo(no);
}
}
启动应用
新增:http://127.0.0.1:8080/repository/add
根据消息日期查询:http://127.0.0.1:8080/repository/find/sql/具体日期
根据消息号查询:http://127.0.0.1:8080//template/find/具体消息号
也可直接利用可视化工具,直接查看数据信息