1.设置pom引用
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.itstudy</groupId> <artifactId>mongodemo</artifactId> <version>1.0-SNAPSHOT</version> <name>mongodemo</name> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-dependencies</artifactId> <version>1.5.9.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <executions> <execution> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> </plugins> </build> </project>
2.在main/resources文件夹,设置application.properties
#非密码链接 spring.data.mongodb.uri=mongodb://localhost:27017/mydb #密码链接 #spring.data.mongodb.uri=mongodb://zzq:123456@localhost:27017/mydb #集群链接 #spring.data.mongodb.uri=mongodb://user:pwd@ip1:port1,ip2:port2/database #显示mongo语句 logging.level.org.springframework.data.mongodb.core=DEBUG
3.定义实体类
package com.itstudy.domain; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Transient; import org.springframework.data.mongodb.core.index.CompoundIndex; import org.springframework.data.mongodb.core.index.CompoundIndexes; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.DBRef; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; import java.util.List; //指定存储到表 @Document(collection = "system_user") //指定复合索引 @CompoundIndexes({ @CompoundIndex(name = "idx_mobile_email", def = "{'mobile': 1, 'email': -1}") }) public class User { //主键 @Id private String id; //设置索引 @Indexed(unique = true) private String userName; private String mobile; private String email; //指定字段名称 @Field("first_name") private String firstName; //不存储到数据库 @Transient private String local; //指定关联数据库 @DBRef private List<Role> roles; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLocal() { return local; } public void setLocal(String local) { this.local = local; } public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } }
使用springboot操作mongodb有两种方式 一种是jpa 另一种是mongoTemplate ,两种各有优点,mongoTemplate更灵活一些。
4使用jpa操作数据库
4.1定义repository
package com.itstudy.dao; import com.itstudy.domain.User; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.stereotype.Repository; import org.springframework.data.domain.Sort; import java.util.Date; import java.util.List; @Repository public interface UserRepository extends MongoRepository<User, String> { List<User> findByUserNameLike(String userName); /** * 排序查询 * * 使用示例 userRepository.findAll(new Sort(new Sort.Order(Sort.Direction.DESC, "userName"))); * 如果定义findAllOrderByUserName() 会报错(Invalid parameter index! You seem to have declare too little query method parameters!) * @return */ List<User> findAll(Sort sort); /** * 分页查询 * * @param userName * @param pageable * @return */ Page<User> queryByUserNameLike(String userName, Pageable pageable); /** * 分页查询 * * @param userName * @param beginTime * @param endTime * @param pageable * @return */ @Query(value = "{\"userName\":{\"$regex\":?0,\"$options\":\"i\"},\"gmtCreate\":{\"$gt\":?1,\"$lt\":?2}}") Page<User> pageQuery(String userName, Date beginTime, Date endTime, Pageable pageable); }
4.2在controller中调用
package com.itstudy.controller; import com.itstudy.dao.UserRepository; import com.itstudy.domain.Role; import com.itstudy.domain.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.text.ParseException; import java.util.Arrays; import java.util.UUID; @RestController @RequestMapping("/index") public class IndexController { final static Logger logger = LoggerFactory.getLogger(IndexController.class); @Autowired UserRepository userRepository; @RequestMapping("/query") public Object getQuery(Integer page, Integer size, String userName) throws ParseException { if (page < 1) { page = 1; } Sort sort = new Sort(Sort.Direction.DESC, "gmtCreate"); Pageable pageable = new PageRequest(page - 1, size, sort); return userRepository.queryByUserNameLike(userName, pageable); } @PostMapping("/create") public void postCreate() { for (int i = 0; i < 20; i++) { User user = new User(); user.setEmail("email@" + Math.random()); user.setUserName("username-" + Math.random()); user.setId(UUID.randomUUID().toString()); user.setMobile("123"); Role role = new Role(); role.setId("100000001"); role.setName("role-test"); user.setRoles(Arrays.asList(role)); userRepository.save(user); } logger.info("添加成功"); } }
5.使用mongoTemplate操作数据库
5.1 定义操作类库
package com.itstudy.dao; import com.itstudy.domain.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; 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.Component; import java.util.Date; import java.util.List; import java.util.regex.Pattern; @Component public class UserDao { @Autowired MongoTemplate mongoTemplate; //一般查询 public User findById(String id) { Query query = new Query(); Criteria criteria = Criteria.where("id").is(id); query.addCriteria(criteria); return mongoTemplate.findOne(query, User.class); } //模糊查询 public List<User> findByUserName(String userName) { Pattern pattern = Pattern.compile("^.*" + userName + ".*$", Pattern.CASE_INSENSITIVE); Criteria criteria = Criteria.where("userName").regex(pattern); Query query = new Query(); query.addCriteria(criteria); return mongoTemplate.find(query, User.class); } public Page<User> pageByUserNameLike(String userName, Pageable pageable) { Pattern pattern = Pattern.compile("^.*" + userName + ".*$", Pattern.CASE_INSENSITIVE); Criteria criteria = Criteria.where("userName").regex(pattern); Query query = new Query(); query.addCriteria(criteria); long total = mongoTemplate.count(query, User.class); List<User> items = mongoTemplate.find(query.with(pageable), User.class); return new PageImpl<User>(items, pageable, total); } public void saveOrUpdate(User item) { mongoTemplate.save(item); } public void updateFirstName(String id, String firstName) { Query query = new Query(); query.addCriteria(Criteria.where("id").is(id)); Update update = new Update(); update.set("first_name", firstName); mongoTemplate.updateFirst(query, update, User.class); } public User delete(String id) { Query query = new Query(); Criteria criteria = Criteria.where("id").is(id); query.addCriteria(criteria); User deleted = mongoTemplate.findAndRemove(query, User.class); return deleted; } public Page<User> pageQuery(String userName, Date beginTime, Date endTime, Pageable pageable) { Query query = new Query(); Criteria criteria = new Criteria(); if (beginTime != null && endTime != null) { criteria.andOperator( Criteria.where("gmtCreate").gte(beginTime), Criteria.where("gmtCreate").lt(endTime) ); } query.addCriteria(criteria); long total = mongoTemplate.count(query, User.class); List<User> items = mongoTemplate.find(query.with(pageable), User.class); return new PageImpl<User>(items, pageable, total); } }
5.2 在controller中调用
package com.itstudy.controller; import com.itstudy.dao.UserDao;import com.itstudy.domain.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Sort; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.text.ParseException; import java.util.Arrays; import java.util.UUID; @RestController @RequestMapping("/home") public class HomeController { final static Logger logger = LoggerFactory.getLogger(IndexController.class); @Autowired UserDao userDao; @RequestMapping("/query") public Object getQuery(Integer page, Integer size, String userName) throws ParseException { if (page < 1) { page = 1; } Sort sort = new Sort(Sort.Direction.DESC, "gmtCreate"); Pageable pageable = new PageRequest(page - 1, size, sort); return userDao.pageByUserNameLike(userName, pageable); } @PostMapping("/create") public void postCreate() { for (int i = 0; i < 20; i++) { User user = new User(); user.setEmail("email@" + Math.random()); user.setUserName("username-" + Math.random()); user.setId(UUID.randomUUID().toString()); user.setMobile("123"); userDao.saveOrUpdate(user); } logger.info("添加成功"); } }
6.启动SpringBoot项目
package com.itstudy; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class App { public static void main(String[] args) { //System.out.println( "Hello World!" ); SpringApplication.run(App.class, args); } }
7.补充
补充: 1.spring-data-mongodb查询结果返回指定字段 方法1 DBObject dbObject = new BasicDBObject(); dbObject.put("status", 1); DBObject fieldObject = new BasicDBObject(); fieldObject.put("catalogName", true); fieldObject.put("_id", true); Query query = new BasicQuery(dbObject, fieldObject); return MongoPagebleUtil.queryAndPagable(query, pageable, getMongoOperations(), ForeCatalog.class); 方法2 @Query(value = "{'status':?0 }", fields = "{ '_id' : 1, 'catalogName' : 1}") List<ForeCatalog> findAllForeCatalogIdAndName(String status); 2.使用多数据源 https://www.cnblogs.com/ityouknow/p/6828919.html