当前位置:网站首页>mongodb客户端操作(MongoRepository)
mongodb客户端操作(MongoRepository)
2022-07-06 17:01:00 【white_while】
orm
jpa
MongoRepository
springboot 整合
- 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
- springboot扫描注解
@EnableMongoRepositories(
basePackages = {"com.jl.ability.*"},
repositoryImplementationPostfix = "Impl")
repositoryImplementationPostfix 默认就是 Impl 后缀,可指定自定义仓储层接口实现类后缀
如mongodb其CustomizedUserRepository指定实现类customizedUserRepositoryImpl
- 定义接口和自定义接口及实现类
interface CustomizedUserRepository {
void someCustomMethod(User user);
}
class CustomizedUserRepositoryImpl implements CustomizedUserRepository {
public void someCustomMethod(User user) {
// Your custom implementation
}
}
@Repository
interface UserRepository extends CrudRepository<User, Long>, CustomizedUserRepository {
// Declare query methods here
}
curd基本操作
实体类
@Data
@Document(collection = "balloon_msg")
public class BalloonMsg {
@Id
private Long id;
private String sid;
private String body;
private Long from;
private int sex;
private Date ctime;
private String accid;
private Integer revNum;
private Integer replyNum;
}
接口
@Repository
public interface BalloonMsgMapper extends MongoRepository<BalloonMsg, Long>, CustomizedBalloonMsgMapper {
List<BalloonMsg> findByFromOrderByIdDesc(Long from, Pageable pageable);
@Query(value="{'$and': [{'from':?0}, {'sid':?1}]}", fields="{'_id': 1}")
List<BalloonMsg> findIdsByFromAndSid(Long from, String sid);
}
注意:
MongoRepository<BalloonMsg, Long>
BalloonMsg为集合映射实体类,Long为主键id类型
基本操作
支持 save,insert,find,delete
查询扩展支持原生查询语句
类似sql:select id from xxx where `from` = from and sid = sid
@Query(value="{'$and': [{'from':?0}, {'sid':?1}]}", fields="{'_id': 1}")
List<BalloonMsg> findIdsByFromAndSid(Long from, String sid);
支持jpa规范方法
类似sql:select * from balloon_msg where `from` = from order by id desc limit x, x
List<BalloonMsg> findByFromOrderByIdDesc(Long from, Pageable pageable);
自定义扩展
public interface CustomizedBalloonMsgMapper {
int incRevNumById(long id, int num);
int incReplyNumById(long id, int num);
}
public class CustomizedBalloonMsgMapperImpl implements CustomizedBalloonMsgMapper {
@Resource
private MongoTemplate mongoTemplate;
@Override
public int incRevNumById(long id, int num) {
Query query = Query.query(Criteria.where("_id").is(id));
Update update = new Update();
update.inc("revNum");
UpdateResult res = mongoTemplate.updateFirst(query, update, BalloonMsg.class);
return (int) res.getModifiedCount();
}
@Override
public int incReplyNumById(long id, int num) {
Query query = Query.query(Criteria.where("_id").is(id));
Update update = new Update();
update.inc("replyNum");
return (int) mongoTemplate.updateFirst(query, update, BalloonMsg.class).getModifiedCount();
}
}
此时的 BalloonMsgMapper 接口包含基本curd和自定义扩展的方法集
@Repository
public interface BalloonMsgMapper extends MongoRepository<BalloonMsg, Long>, CustomizedBalloonMsgMapper{
...
}
注意:
- 通用操作使用 Spring Data Repositories 其 MongoRepository
- 自定义扩展使用 MongoTemplate,通过自定义扩展接口接入
边栏推荐
- 【YoloV5 6.0|6.1 部署 TensorRT到torchserve】环境搭建|模型转换|engine模型部署(详细的packet文件编写方法)
- 509 certificat basé sur Go
- Liuyongxin report | microbiome data analysis and science communication (7:30 p.m.)
- Advanced learning of MySQL -- basics -- multi table query -- external connection
- 2022/2/10 summary
- Things like random
- 2021 SASE integration strategic roadmap (I)
- Leetcode (547) - number of provinces
- Threejs image deformation enlarge full screen animation JS special effect
- 【JokerのZYNQ7020】AXI_ EMC。
猜你喜欢
[yolov5 6.0 | 6.1 deploy tensorrt to torch serve] environment construction | model transformation | engine model deployment (detailed packet file writing method)
2021 SASE integration strategic roadmap (I)
Data analysis course notes (III) array shape and calculation, numpy storage / reading data, indexing, slicing and splicing
System activity monitor ISTAT menus 6.61 (1185) Chinese repair
@TableId can‘t more than one in Class: “com.example.CloseContactSearcher.entity.Activity“.
JWT signature does not match locally computed signature. JWT validity cannot be asserted and should
基于GO语言实现的X.509证书
The programmer resigned and was sentenced to 10 months for deleting the code. Jingdong came home and said that it took 30000 to restore the database. Netizen: This is really a revenge
How to judge whether an element in an array contains all attribute values of an object
File and image comparison tool kaleidoscope latest download
随机推荐
什么是时间
深度学习之环境配置 jupyter notebook
Threejs image deformation enlarge full screen animation JS special effect
Advanced learning of MySQL -- basics -- multi table query -- inner join
Stm32f407 ------- SPI communication
Leecode brush question record sword finger offer 56 - ii Number of occurrences of numbers in the array II
基于GO语言实现的X.509证书
如何判断一个数组中的元素包含一个对象的所有属性值
2022/2/10 summary
Policy Gradient Methods
uniapp实现从本地上传头像并显示,同时将头像转化为base64格式存储在mysql数据库中
37頁數字鄉村振興智慧農業整體規劃建設方案
JWT signature does not match locally computed signature. JWT validity cannot be asserted and should
What can the interactive slide screen demonstration bring to the enterprise exhibition hall
Interface (interface related meaning, different abstract classes, interface callback)
Clipboard management tool paste Chinese version
准备好在CI/CD中自动化持续部署了吗?
Alexnet experiment encounters: loss Nan, train ACC 0.100, test ACC 0.100
Learn to use code to generate beautiful interface documents!!!
Data analysis course notes (V) common statistical methods, data and spelling, index and composite index