当前位置:网站首页>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,通过自定义扩展接口接入
边栏推荐
- Three methods to realize JS asynchronous loading
- JS import excel & Export Excel
- 学习光线跟踪一样的自3D表征Ego3RT
- Jenkins' user credentials plug-in installation
- 37 pages Digital Village revitalization intelligent agriculture Comprehensive Planning and Construction Scheme
- Mujoco finite state machine and trajectory tracking
- Devops can help reduce technology debt in ten ways
- uniapp实现从本地上传头像并显示,同时将头像转化为base64格式存储在mysql数据库中
- Advanced learning of MySQL -- Fundamentals -- four characteristics of transactions
- Hero League | King | cross the line of fire BGM AI score competition sharing
猜你喜欢
Zynq transplant ucosiii
X.509 certificate based on go language
Three application characteristics of immersive projection in offline display
37 pages Digital Village revitalization intelligent agriculture Comprehensive Planning and Construction Scheme
stm32F407-------DAC数模转换
AI超清修复出黄家驹眼里的光、LeCun大佬《深度学习》课程生还报告、绝美画作只需一行代码、AI最新论文 | ShowMeAI资讯日报 #07.06
Clipboard management tool paste Chinese version
The difference between redirectto and navigateto in uniapp
2022 PMP project management examination agile knowledge points (9)
@TableId can‘t more than one in Class: “com.example.CloseContactSearcher.entity.Activity“.
随机推荐
Quaternion attitude calculation of madgwick
Advantages and disadvantages of code cloning
Sword finger offer 26 Substructure of tree
Encryption algorithm - password security
【软件逆向-求解flag】内存获取、逆变换操作、线性变换、约束求解
48 page digital government smart government all in one solution
Rails 4 asset pipeline vendor asset images are not precompiled
Leecode brush questions record sword finger offer 11 Rotate the minimum number of the array
48页数字政府智慧政务一网通办解决方案
Geo data mining (III) enrichment analysis of go and KEGG using David database
Threejs image deformation enlarge full screen animation JS special effect
Use mujoco to simulate Cassie robot
【vulnhub】presidential1
Lombok 同时使⽤ @Data 和 @Builder 的坑,你中招没?
How to get started and improve test development?
Set (generic & list & Set & custom sort)
2022/2/12 summary
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
AI super clear repair resurfaces the light in Huang Jiaju's eyes, Lecun boss's "deep learning" course survival report, beautiful paintings only need one line of code, AI's latest paper | showmeai info
37 pages Digital Village revitalization intelligent agriculture Comprehensive Planning and Construction Scheme