依赖:
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-data-mongodb -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
配置
application.properties:
#spring.data.mongodb.uri=mongodb://localhost:27017/sea
spring.data.mongodb.uri=mongodb://用户名:密码@localhost:27017/sea或者:
#spring.data.mongodb.uri=mongodb://userName:password@ip:port/database
spring.data.mongodb.database=ELSA_MILESTONE_SUBSCRIPTION_SERVICE
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
#spring.data.mongodb.username=mongodb
#spring.data.mongodb.password=root
方式:1: 使用
@Autowired
private MongoTemplate mongoTemplate;
eg:
package com.icil.dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;
import com.icil.domain.UserEntity;
@Repository
public class UserDAO {
@Autowired
private MongoTemplate mongoTemplate;
/**
* 创建对象
* @param user
*/
public void saveUser(UserEntity user) {
mongoTemplate.save(user);
}
/**
* 根据用户名查询对象
* @param userName
* @return
*/
public UserEntity findUserByUserName(String userName) {
Query query=new Query(Criteria.where("userName").is(userName));
UserEntity user = mongoTemplate.findOne(query , UserEntity.class);
return user;
}
/**
* 更新对象
* @param user
*/
public void updateUser(UserEntity user) {
Query query=new Query(Criteria.where("id").is(user.getId()));
Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord());
//更新查询返回结果集的第一条
mongoTemplate.updateFirst(query,update,UserEntity.class);
//更新查询返回结果集的所有
// mongoTemplate.updateMulti(query,update,UserEntity.class);
}
/**
* 删除对象
* @param id
*/
public void deleteUserById(Long id) {
Query query=new Query(Criteria.where("id").is(id));
mongoTemplate.remove(query,UserEntity.class);
}
}
View Code
高频使用: 多条件 动态 (类似mybtis)
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void testNameQuery() throws Exception {
//collectionName -->
Criteria criteria1 = Criteria.where("collName").is("lzd_work_table_collection");
Criteria criteria2 = Criteria.where("status").is("RCS");
Query query = new Query();
query.addCriteria(criteria1);
query.addCriteria(criteria2);
System.err.println(query);
// Query query=new Query(Criteria.where("status").is("RSC"));
// public <T> List<T> find(Query query, Class<T> entityClass, String collectionName) {
List<MilestoneInfo> find = mongoTemplate.find(query,MilestoneInfo.class);
System.err.println("#######################");
System.err.println(find);
}
**方式2:extends MongoRepository
**
eg:
UserRepository.java
package com.sea.test.repository;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.data.mongodb.repository.Query;
import com.sea.test.pojo.User;
public interface UserRepository extends MongoRepository<User, Long> {
/**
* Like(模糊查询)
* {"username" : name} ( name as regex)
* */
List<User> findByUsernameLike(String username);
List<User> findByUsernameLike(String username,PageRequest pageable);
/**
* Like(模糊查询)
* {"username" : name}
* */
List<User> findByUsername(String username);
/**
* GreaterThan(大于)
* {"age" : {"$gt" : age}}
* */
List<User> findByAgeGreaterThan(int age);
/**
* LessThan(小于)
* {"age" : {"$lt" : age}}
* */
List<User> findByAgeLessThan(int age);
/**
* Between(在...之间)
* {{"age" : {"$gt" : from, "$lt" : to}}
* */
List<User> findByAgeBetween(int from, int to);
/**
* IsNotNull, NotNull(是否非空)
* {"username" : {"$ne" : null}}
* */
List<User> findByUsernameNotNull();
/**
* IsNull, Null(是否为空)
* {"username" : null}
* */
List<User> findByUsernameNull();
/**
* Not(不包含)
* {"username" : {"$ne" : name}}
* */
List<User> findByUsernameNot(String name);
/**
* Near(查询地理位置相近的)
* {"location" : {"$near" : [x,y]}}
* */
// findByLocationNear(Point point)
/**
* Within(在地理位置范围内的)
* {"location" : {"$within" : {"$center" : [ [x, y], distance]}}}
* */
//findByLocationWithin(Circle circle)
/**
* Within(在地理位置范围内的)
* {"location" : {"$within" : {"$box" : [ [x1, y1], x2, y2]}}}
* */
// findByLocationWithin(Box box)
/**
*
* @param name
* @param age
* @param page
* @return
*/
@Query("{\"username\":{\"$regex\":?0}, \"age\": ?1}")
Page<User> findByNameAndAgeRange(String name,int age,Pageable page);
/**
*
* @param name
* @param ageFrom
* @param ageTo
* @param page
* @return
*/
@Query(value="{\"username\":{\"$regex\":?0},\"age\":{\"$gte\":?1,\"$lte\": ?2}}")
Page<User> findByNameAndAgeRange2(String name,int ageFrom,int ageTo,Pageable page);
@Query(value="{\"username\":{\"$regex\":?0},\"age\":{\"$gte\":?1,\"$lte\": ?2}}",fields="{\"username\" : 1, \"age\" : 1}")
Page<User> findByNameAndAgeRange3(String name,int ageFrom,int ageTo,Pageable page);
}
View Code
User:
package com.sea.test.pojo;
import java.io.Serializable;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.stereotype.Component;
import com.sea.test.annotation.AutoIncKey;
import com.sea.test.annotation.aop.SeaAnnotion;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
@Component
@Document(collection = "My_user") //指定别名
public class User implements Serializable {
private static final long serialVersionUID = -1L;
@Id //指定id
@AutoIncKey //自定义注解
private Long id;
@Field("userName") //指定匹配关系
private String username;
private Integer age;
@SeaAnnotion()
public Long getId() {
return id;
}
@SeaAnnotion()
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public User() {
super();
}
public User(Long id, String username) {
super();
this.id = id;
this.username = username;
}
public User(Long id, String username, Integer age) {
super();
this.id = id;
this.username = username;
this.age = age;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", age=" + age + "]";
}
}
View Code
controller : 参考https://blog.csdn.net/weixin\_39214304/article/details/84791953
package com.sea.test.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.sea.test.pojo.User;
import com.sea.test.repository.UserRepository;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@ResponseStatus(HttpStatus.CREATED)
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public User createUser(@RequestBody User user) {
return userRepository.save(user);
}
/**
* 根据id查询
*
* @param id
* @return
*/
@GetMapping(value = "/{id}")
public User readUserById(@PathVariable("id") Long id) {
return userRepository.findById(id).get();
}
@GetMapping(value = "/all")
public List<User> getAll() {
System.err.println("### enter into getall emthod ###");
return userRepository.findAll();
}
/**
* 根据一个或者多个属性查询单个结果
*
* @param name
* @return
*/
@GetMapping(value = "/name/{name}")
public User readUserByName(@PathVariable("name") String name) {
User user = new User();
user.setUsername(name);
ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("age", "createTime");
Example<User> example = Example.of(user, matcher);
return userRepository.findOne(example).get();
}
/**
* 根据一个或者多个属性分页查询
*
* @param pageNumber
* @param pageSize
* @return
*/
@GetMapping(value = "/page/{pageNumber}/pagesize/{pageSize}/name/{name}")
public Page<User> readUsersByPage(@PathVariable("pageNumber") int pageNumber,
@PathVariable("pageSize") int pageSize, @PathVariable("name") String name) {
User user = new User();
user.setUsername(name);
ExampleMatcher matcher = ExampleMatcher.matching().withIgnorePaths("age", "createTime");
Example<User> example = Example.of(user, matcher);
if (pageNumber < 1) {
pageNumber = 1;
} else if (pageSize == 0) {
pageSize = 20;
}
PageRequest pageable = PageRequest.of(pageNumber - 1, pageSize);
return userRepository.findAll(example, pageable);
}
/**
* 根据用户年龄升序排序
*
* @return
*/
@GetMapping("/get")
public List<User> readUsers() {
System.err.println("### enter into readUser emthod ###");
Order order = new Order(Direction.ASC, "age");
Sort sort = Sort.by(order);
return userRepository.findAll(sort);
}
/**
* 模糊查询带分页
*
* @param pageNumber
* @param pageSize
* @param keyWords
* @return
*/
@GetMapping(value = "/page/{pageNumber}/pagesize/{pageSize}/keyword/{keyWords}")
public Page<User> readUsersByKeywords(@PathVariable("pageNumber") int pageNumber,
@PathVariable("pageSize") int pageSize, @PathVariable("keyWords") String keyWords) {
if (keyWords == null) {
keyWords = "";
}
if (pageNumber < 1) {
pageNumber = 1;
} else if (pageSize == 0) {
pageSize = 20;
}
PageRequest pageable = PageRequest.of(pageNumber - 1, pageSize);
return (Page<User>) userRepository.findByUsernameLike(keyWords, pageable);
}
@ResponseStatus(HttpStatus.OK)
@DeleteMapping(value = "/{id}")
public void removeUser(@PathVariable("id") Long id) {
userRepository.deleteById(id);
}
}
View Code