最近的项目用了Mongodb,网上的用法大多都是七零八落的没有一个统一性,自己大概整理了下,项目中的相关配置就不叙述了,由于spring boot的快捷开发方式,所以spring boot项目中要使用Mongodb,只需要添加依赖和配置application.properties文件即可。整和方式一共有两种,一种是JPA的快捷方式,还有一种是实现MongoTemplate中的方法。
一、spring boot Mongodb JPA
这种是mongodb的快捷开发方式,类似于spring data jpa的操作,通过使用spring boot约定的规范来定义名字,与HibernateRepository类似,通过继承MongoRepository接口,我们可以非常方便地实现对一个对象的增删改查,要使用Repository的功能,先继承MongoRepository<T, TD>接口,其中T为仓库保存的bean类,TD为该bean的唯一标识的类型,一般为ObjectId。之后在service中注入该接口就可以使用,无需实现里面的方法,spring会根据定义的规则自动生成。
创建一个bean,其中@id是这种表的主键,user就是表的名字
import org.springframework.data.annotation.Id; public class User { @Id private Long id; private String name; private Integer userage; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getUserage() { return userage; } public void setUserage(Integer userage) { this.userage = userage; } public User(Long id, String name, Integer userage) { super(); this.id = id; this.name = name; this.userage = userage; } }