MongoRepository
与HibernateRepository类似,通过继承MongoRepository接口,我们可以非常方便地实现对一个对象的增删改查,要使用Repository的功能,先继承MongoRepository<T, TD>接口,其中T为仓库保存的bean类,TD为该bean的唯一标识的类型,一般为ObjectId。之后在service中注入该接口就可以使用,无需实现里面的方法,spring会根据定义的规则自动生成。
Springboot与MongoRepository整合
1.1 pom.xml 加入mongodb依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
1.2 appliaction.yml 加入mongodb配置,即使数据库(springboot-db)不存在,系统也会自动创建
spring:
data:
mongodb:
uri: mongodb://localhost:27017/springboot-db
1.3 创建Model对象
public class ShopDO implements Serializable{
public Long id;
public String name;
public ShopDO(){
}
public ShopDO(Long id,String name){
this.id = id;
this.name = name;
}
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;
}
@Override
public String toString() {
return String.format(
"shopDO[id=%s, name='%s']",
id, name);
}
}
1.4 创建服务对象
public interface ShopRepository extends MongoRepository<ShopDO,String>{
public ShopDO getShopById(Long id);
public List<ShopDO> getByName(String name);
}
1.5 测试
@SpringBootApplication
public class Application implements CommandLineRunner{
@Autowired
private ShopRepository repository;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Override
public void run(String... strings) throws Exception {
repository.deleteAll();
// save a couple of customers
repository.save(new ShopDO(1L, "Smith"));
repository.save(new ShopDO(2L, "qingzhi"));
// fetch all customers
System.out.println("ShopDO found with findAll():");
System.out.println("-------------------------------");
for (ShopDO shopDO : repository.findAll()) {
System.out.println(shopDO);
}
System.out.println();
// fetch an individual customer
System.out.println("ShopDO found with getById('1L'):");
System.out.println("--------------------------------");
System.out.println(repository.getShopById(1L));
System.out.println("ShopDO found with getByName('Smith'):");
System.out.println("--------------------------------");
for (ShopDO shopDO : repository.getByName("qingzhi")) {
System.out.println(shopDO.getId());
}
}
}
控制台输出:
ShopDO found with findAll():
-------------------------------
Customer[id=1, name='Smith']
Customer[id=2, name='qingzhi']
ShopDO found with getById('1L'):
--------------------------------
Customer[id=1, name='Smith']
ShopDO found with getByName('Smith'):
--------------------------------
2