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
示例总结
@RestController @RequestMapping("/") public class IndexController { private MongoTemplate mongoTemplate; @RequestMapping("/index") public void test() { UserTest userTest = new UserTest(); userTest.setId("1"); userTest.setName("abc"); //用于更新个别字段 Query query = Query.query(Criteria.byExample(userTest)); System.out.println(query.toString()); } public PageImpl<UserTest> test07() { Query query = new Query(); int pageIndex = 1; int pageSize = 20; //分页 Pageable pageable = new PageRequest(pageIndex, pageSize); query.with(pageable); //排序 query.with(new Sort(Sort.Direction.ASC, "ts", "id")); //总数 long count = mongoTemplate.count(query, UserTest.class); //列表 List<UserTest> userTestList = mongoTemplate.find(query, UserTest.class); PageImpl<UserTest> page = new PageImpl<UserTest>(userTestList,pageable,count); return page; } public void test06() { UserTest userTest = new UserTest(); userTest.setId("1"); userTest.setName("abc"); //如果不存在,会插入。 // 如果存在,会进行替换更新 mongoTemplate.save(userTest); //用于更新个别字段 Query query = Query.query(Criteria.where("id").is("1")); Update update = Update.update("new_field", "value"); mongoTemplate.updateFirst(query, update, UserTest.class); } public void test05() { Criteria criteria = new Criteria(); criteria.andOperator(Criteria.where("remark").is("remark"), Criteria.where("passworkd").is("password")); criteria.orOperator(Criteria.where("id").is("abc"), Criteria.where("name").is("abc")); Query query = new Query(); query.addCriteria(criteria); System.out.println(query.toString()); //输出 //Query: { "$and" : [ { "remark" : "remark"} , { "passworkd" : "password"}] , "$or" : [ { "id" : "abc"} , { "name" : "abc"}]}, Fields: null, Sort: null } public void test04() { Criteria criteria = new Criteria(); criteria.andOperator(Criteria.where("remark").is("remark"), Criteria.where("passworkd").is("password")); Query query = new Query(); query.addCriteria(criteria); query.addCriteria(Criteria.where("id").is("abc")); System.out.println(query.toString()); //输出 //Query: { "$and" : [ { "remark" : "remark"} , { "passworkd" : "password"}] , "id" : "abc"}, Fields: null, Sort: null } public void test03() { Criteria criteria = new Criteria(); criteria.andOperator(Criteria.where("remark").is("remark"), Criteria.where("passworkd").is("password")); Criteria criteria2 = new Criteria(); criteria2.orOperator(Criteria.where("id").is("abc"), Criteria.where("name").is("abc")); Query query = new Query(); query.addCriteria(criteria); query.addCriteria(criteria2); System.out.println(query.toString()); //输出 } public void test02() { Criteria criteria = new Criteria(); criteria.andOperator(Criteria.where("remark").is("remark"), Criteria.where("passworkd").is("password")); Query query = new Query(); query.addCriteria(criteria); System.out.println(query.toString()); //输出 //Query: { "$and" : [ { "remark" : "remark"} , { "passworkd" : "password"}]}, Fields: null, Sort: null } //这种调用是无效的 public void test01() { Criteria criteria = new Criteria(); criteria.where("name").is("name"); Query query = new Query(); query.addCriteria(criteria); System.out.println(query.toString()); //输出 //Query: { }, Fields: null, Sort: null //原因 where是静态方法 //criteria对像,仅能调用 非静态方法 如 orOperation andOperation //其它情况下,只使用query.add(Criteria.where("").is(""))即可,可以多次调用 } }
动态添加条件
动态添加条件两种方法: 方法1 criteria.and String nickName = ""; String sex = ""; String authorizerAppId=""; String tantenId=""; Criteria criteria = Criteria.where("authorizer_appid").is(authorizerAppId).and("tanten_id").is(tantenId); if (nickName != null && nickName.trim().length() > 0) { Pattern pattern = Pattern.compile("^.*" + nickName + ".*$", Pattern.CASE_INSENSITIVE); criteria.and("nickname").regex(pattern); } if (sex != null && sex.trim().length() > 0) { criteria.and("sex").is(sex); } Query query = Query.query(criteria); logger.info("criteria:{}", query.toString()); 输出: { "authorizer_appid" : "3" , "tanten_id" : "4" , "nickname" : { "$regex" : "^.*1.*$" , "$options" : "i"} , "sex" : "2"} 方法2:query.addCriteria() String nickName = "1"; String sex = "2"; String authorizerAppId="3"; String tantenId="4"; Criteria criteria = Criteria.where("authorizer_appid").is(authorizerAppId).and("tanten_id").is(tantenId); Query query = Query.query(criteria); if (nickName != null && nickName.trim().length() > 0) { Pattern pattern = Pattern.compile("^.*" + nickName + ".*$", Pattern.CASE_INSENSITIVE); query.addCriteria(Criteria.where("nickname").regex(pattern)); } if (sex != null && sex.trim().length() > 0) { query.addCriteria(Criteria.where("sex").is(sex)); } logger.info("criteria:{}", query.toString()); 输出: { "authorizer_appid" : "3" , "tanten_id" : "4" , "nickname" : { "$regex" : "^.*1.*$" , "$options" : "i"} , "sex" : "2"}