springboot之mongo

原文链接:https://blog.csdn.net/qq_34177039/article/details/88536704

https://blog.csdn.net/qq_38288606/article/details/78673528

1、依赖

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>

<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

2、application.xml
#通常是自己建立的database
spring.data.mongodb.database=springdata
spring.data.mongodb.host=192.168.127.128
spring.data.mongodb.password=admin
spring.data.mongodb.username=admin
spring.data.mongodb.port=27017
#认证的用户
spring.data.mongodb.authentication-database=admin
3、编写保存实体Order
@Data
@Document(collection = "order")
public class Order {
@Id
private String id;
private String orderId;
private String content;
private Date date;

}
4、两种不同形式的使用方式 OrderDao (一种用Repository,一种tempalate)

如果只是用简单的CRUD操作,则不需要添加其他的方法,MongoRepository提供的方法足够我们使用。

public interface PersonRepository extends MongoRepository<Person, String>{
}

@Repository
public class OrderDao2 {

@Autowired
private MongoTemplate mongoTemplate;

/**
* 创建对象
*/
public void saveorder(Order order) {
mongoTemplate.save(order);
}


/**
* 根据用户名查询对象
* @return
*/
public Order findTestByName(String name) {
Query query=new Query(Criteria.where("name").is(name));
Order order = mongoTemplate.findOne(query , Order.class);
return order;
}

/**
* 更新对象
*/
public void updateTest(Order order) {
Query query=new Query(Criteria.where("id").is(order.getId()));
Update update= new Update().set("content", order.getContent()).set("date", order.getDate());
//更新查询返回结果集的第一条
mongoTemplate.updateFirst(query,update,Order.class);
//更新查询返回结果集的所有
// mongoTemplate.updateMulti(query,update,TestEntity.class);
}

/**
* 删除对象
* @param id
*/
public void deleteTestById(Integer id) {
Query query=new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query,Order.class);
}

public void findAll() {
List<Order> all = mongoTemplate.findAll(Order.class,"order");
System.out.println(all);
}

2.仓库:
如果只是用简单的CRUD操作,则不需要添加其他的方法,MongoRepository提供的方法足够我们使用。

public interface PersonRepository extends MongoRepository<Person, String>{
}
1
2
3.利用MongoRepository中的查询进行操作
首先,在service层中,将PersonRepository注入到service类中

public class PersonServiceImpl implements IPersonService{
@Autowired
private PersonRepository personRepository;
}
1
2
3
4
1)查询所有的数据:

public List<Person> queryAll() throws Exception {
return personRepository.findAll();
}
1
2
3
2)查询所有的数据带分页:
方法为:Page<?> findAll(Pageable pageable); 该方法中的参数是一个借口,我们需要构造一个子对象,即:PageRequest对象,这个对象中有两个属性,第一个是页码,第二个是页面大小。注意:页码在mongodb中是从0开始的。

public Page<Person> queryAllByPage(int page,int rows) throws Exception {
PageRequest pageRequest = new PageRequest(page-1,rows);
return personRepository.findAll(pageRequest);
}
1
2
3
4
3)查询所有的数据的数量:

public int count() throws Exception {
long size = personRepository.count();
int count = Integer.valueOf(String.valueOf(size));
return count;
}
1
2
3
4
5
4)根据实体类中的属性进行查询:
当需要根据实体类中的属性查询时,MongoRepository提供的方法已经不能满足,我们需要在PersonRepository仓库中定义方法,定义方法名的规则为:find + By + 属性名(首字母大写),如:根据姓名查询Person
仓库中添加的方法:

public Person findByName(String name);
1
它会自动根据name查询。
service中的方法:

public void queryByFirstName(String name) throws Exception {
Person person = personRepository.findByName(name);
}
1
2
3
若根据其他属性查询,方法类似!

5)根据实体类中的属性进行模糊查询:
当需要根据实体类中的属性进行模糊查询时,我们也需要在PersonRepository仓库中定义方法,模糊查询定义方法名的规则为:find + By + 属性名(首字母大写) + Like,如:根据姓名进行模糊查询Person
仓库中添加的方法:

public List<Person> findByNameLike(String name);
1
service中的方法:
在service中直接调用仓库中我们刚才定义的方法即可!

public List<Person> queryByFirstNameLike(String name) throws Exception {
return personRepository.findByNameLike(name);
}
1
2
3
6)根据实体类中的属性进行模糊查询带分页:
带分页的模糊查询,其实是把模糊查询以及分页进行合并,同时我们也需要在PersonRepository仓库中定义方法,定义方法名的规则和模糊查询的规则一致,只是参数不同而已。
仓库中添加的方法:

public Page<Person> findByNameLike(String name,Pageable pageable);
1
在service中对仓库中的方法的调用:

public List<Person> queryByNameAndPage(int page, int rows, String name) throws Exception {
PageRequest pageRequest = new PageRequest(page-1,rows);
return personRepository.findByNameLike(name, pageRequest).getContent();
}
1
2
3
4
7)根据实体类中的属性进行模糊查询带分页,同时指定返回的键(数据库中的key,实体类中的属性):
解释一下什么是指定返回的键:也就是说当我们进行带分页的模糊查询时,不想返回数据库中的所有字段,只是返回一部分字段。例如:只返回Person中的id和name,不返回age.
若想指定返回的键,我们需要在PersonRepository中添加方法,同时使用注解@Query。
仓库中定义的方法:

@Query(value="{'name':?0}",fields="{'name':1}")
public Page<Person> findByNameLike(String name,Pageable pageable);
1
2
其中value是查询的条件,?0这个是占位符,对应着方法中参数中的第一个参数,如果对应的是第二个参数则为?1。fields是我们指定的返回字段,其中id是自动返回的,不用我们指定,bson中{‘name’:1}的1代表true,也就是代表返回的意思。
在service中对仓库中的方法的调用:

public List<Person> queryByNameAndPage(int page, int rows, String name) throws Exception {
PageRequest pageRequest = new PageRequest(page-1,rows);
return personRepository.findByNameLike(name, pageRequest).getContent();
}
1
2
3
4
特殊查询:
1)需要查询所有数据,同时指定返回的键
当我们需要查询所有数据,同时需要指定返回的键时,则不能使用仓库中自带的findAll()方法了。我们可以查询所有id不为空的数据,同时指定返回的键。当我们需要根据一个key且该key不为空进行查询,方法名的定义规则为:find + By + 属性名(首字母大写) + NotNull。
仓库中定义的方法:

@Query(value="{'_id':{'$ne':null}}",fields="{'name':1}")
public Page<Person> findByIdNotNull(Pageable pageable);
1
2
service中调用仓库中的方法:

public List<Person> queryAll(int page, int rows) throws Exception {
PageRequest pageRequest = new PageRequest(page-1,rows);
return personRepository.findByIdNotNull(pageRequest).getContent();
}
1
2
3
4
2)MongoDB的其他查询不一一列举,但将java中的仓库定义的方法名的规则列举如下,使用时将仓库中方法上的注解@Query中的value进行适当泰欧正即可。

GreaterThan(大于)
方法名举例:findByAgeGreaterThan(int age)
query中的value举例:{“age” : {"$gt" : age}}

LessThan(小于)
方法名举例:findByAgeLessThan(int age)
query中的value举例:{“age” : {"$lt" : age}}

Between(在…之间)
方法名举例:findByAgeBetween(int from, int to)
query中的value举例:{“age” : {“[Math Processing Error]gt&quot; : from, &quot;gt":from,"lt” : to}}

Not(不包含)
方法名举例:findByNameNot(String name)
query中的value举例:{“age” : {"$ne" : name}}

Near(查询地理位置相近的)
方法名举例:findByLocationNear(Point point)
query中的value举例:{“location” : {"$near" : [x,y]}}

原文地址:https://www.cnblogs.com/fswhq/p/12120597.html