最好的springboot与最好的mongodb邂逅
这段时间大家都说mongodb很火,恩啦,本人也是怎么认为的,不过之前没有了解过mongodb的魅力,适当抽了一下时间和大家了解了解。
接下来,咱二话不说,直接上代码
咱先写pom.xml
<?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.springboot.mongo</groupId>
<artifactId>springboot_mongoDB</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>springboot_mongoDB</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.BUILD-SNAPSHOT</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--引入mongoDB的依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.39</version>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
</project>
咱来写一下配置把
spring.data.mongodb.host=127.0.0.1 spring.data.mongodb.username=spring spring.data.mongodb.password=123456 spring.data.mongodb.database=springboot spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp spring.mvc.static-path-pattern=/static/** server.port=8081
咱再搞个接口,继承的是MongoRepository接口自带的api
package com.springboot.mongo.repository; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; import com.springboot.mongo.pojo.User; //标识为DAO层 @Repository // 拓展MongoRepository接口 public interface UserRepository extends MongoRepository<User, Long> { /** * 符合JPA规范命名方法,则不需要再实现该方法也可用 意在对满足条件的文档按照用户名称进行模糊查询 * * @param userName * 用户名称 * @return 满足条件的用户信息 */ List<User> findByUserNameLike(String userName); /** * 使用自定义方法 * 根据编号或者用户名查找用户 * @param id 编号 * @param userName 用户名 * @return 用户信息 */ User findUserByIdOrUserName(Long id,String userName); }
写一个此接口的实现把,
package com.springboot.mongo.repository.impl; 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.stereotype.Repository; import com.springboot.mongo.pojo.User; /** * Spring约定 在Spring 中只要定义一个“接口名称+Impl”的类,并且提供与接口定义相同的方法,Spring就会自动找到这个类对应的方法 * 作为JPA接口定义的实现 * * @author apple * */ // 定义为数据访问层 @Repository public class UserRepositoryImpl { @Autowired private MongoTemplate mongoTemplate = null; // 注意方法名称与接口定义也需要保持一致 public User findUserByIdOrUserName(Long id, String userName) { // 根据id查询准则 Criteria criteriaId = Criteria.where("id").is(id); // 构造用户名查询准则 Criteria criteriaUserName = Criteria.where("userName").is(userName); Criteria criteria = new Criteria(); // 使用$or 操作符关联两个条件,形成或关系 criteria.orOperator(criteriaId, criteriaUserName); Query query = Query.query(criteria); // 执行查询返回结果 return mongoTemplate.findOne(query, User.class); } }
哦,突然忘了,咱再写一个实体类
在这之前,再来个
package com.springboot.mongo; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(SpringbootMongoDbApplication.class); } }
现在开始写一个实体了
package com.springboot.mongo.pojo; import java.io.Serializable; import java.util.List; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; //标识为MongoDB文档 @Document public class User implements Serializable { /** * */ private static final long serialVersionUID = 1863266251887464830L; // MongoDB文档编号,主键 @Id private Long id; // 在MongoDB中使用user_name保存属性 @Field("user_name") private String userName = null; private String note = null; // 角色列表 private List<Role> roles; public List<Role> getRoles() { return roles; } public void setRoles(List<Role> roles) { this.roles = roles; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
写一个Role实体
package com.springboot.mongo.pojo; import java.io.Serializable; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; @Document public class Role implements Serializable{ /** * */ private static final long serialVersionUID = 6618232253849345782L; private Long id; @Field("role_name") private String roleName=null; private String note=null; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } }
开始写service
先来个接口
package com.springboot.mongo.service; import java.util.List; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import com.springboot.mongo.pojo.User; public interface UserService { public void saveUser(User user); public DeleteResult deleteUser(Long id); public List<User> findUser(String userName, String note, int skip, int limit); public UpdateResult updateUser(Long id, String userName, String note); public User getUser(Long id); }
再来个实现
package com.springboot.mongo.service.impl; import java.util.List; 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.Service; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import com.springboot.mongo.pojo.User; import com.springboot.mongo.service.UserService; @Service public class UserServiceImpl implements UserService { // 注入MongoTemplate对象 @Autowired private MongoTemplate mongoTemplate = null; @Override public void saveUser(User user) { // 使用名称为user 文档保存用户信息 mongoTemplate.save(user, "user"); // 如果文档采用类名首字母小写,则可以这样写 // mongoTemplate.save(user); } /** * 删除文档数据 */ @Override public DeleteResult deleteUser(Long id) { // 构建id相等的条件准则 Criteria criteriaId = Criteria.where("id").is(id); // 查询对象 Query queryId = Query.query(criteriaId); // 删除用户 DeleteResult result = mongoTemplate.remove(queryId, User.class); return result; } @Override public List<User> findUser(String userName, String note, int skip, int limit) { // 将用户名称和备注设置为模糊查询准则 Criteria criteria = Criteria.where("userName").regex(userName).and("note").regex(note); // 构建查询条件,并设置分页跳过前skip个,至少返回limit个 Query query = Query.query(criteria).limit(limit).skip(skip); // 执行 List<User> users = mongoTemplate.find(query, User.class); return users; } // 更新文档操作 @Override public UpdateResult updateUser(Long id, String userName, String note) { // 确定要更新的对象 Criteria criteriaId = Criteria.where("id").is(id); Query query = Query.query(criteriaId); // 定义更新对象,后续可变的字符串代表排除在的属性 Update update = Update.update("userName", userName); update.set("note", note); // 更新第一个文档 UpdateResult result = mongoTemplate.updateFirst(query, update, User.class); // 更新多个对象 // UpdateResult result = mongoTemplate.updateMulti(query, update, User.class); return result; } @Override public User getUser(Long id) { return mongoTemplate.findById(id, User.class); } }
现在咱写Controller了
package com.springboot.mongo.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.mongodb.client.result.DeleteResult; import com.mongodb.client.result.UpdateResult; import com.springboot.mongo.pojo.User; import com.springboot.mongo.service.UserService; @Controller @RequestMapping("/user") public class UserControllers1 { @Autowired private UserService userService = null; // 跳转到测试页面 @RequestMapping("/page") public String page() { return "user"; } /** * 保存(新增或者更新)用户 * * @param user * 用户 * @return 用户信息 */ @RequestMapping("/save") @ResponseBody public User saveUser(@RequestBody User user) { System.out.println("_____________插入用户___________________"); userService.saveUser(user); return user; } /** * 获取用户 * * @param id * 用户主键 * @return 用户信息 */ @RequestMapping("/get") @ResponseBody public User getUser(Long id) { User user = userService.getUser(id); return user; } /** * 查询用户 * * @param userName * 用户名称 * @param note * 备注 * @param skip * 跳过用户个数 * @param limit * 限制返回用户个数 * @return */ @RequestMapping("/find") @ResponseBody public List<User> addUser(String userName, String note, Integer skip, Integer limit) { List<User> userList = userService.findUser(userName, note, skip, limit); return userList; } /** * 更新用户部分属性 * * @param id * 用户编号 * @param userName * 用户名称 * @param note * 备注 * @return 更新结果 */ @RequestMapping("/update") @ResponseBody public UpdateResult updateUser(Long id, String userName, String note) { return userService.updateUser(id, userName, note); } /** * 删除用户 * * @param id * 用户主键 * @return 删除结果 */ @RequestMapping("/delete") @ResponseBody public DeleteResult deleteUser(Long id) { return userService.deleteUser(id); }
启动类
package com.springboot.mongo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; @SpringBootApplication // 指定扫描的包,用户继承了MongoRepository的接口 @EnableMongoRepositories(basePackages = "com.springboot.mongo.repository", repositoryImplementationPostfix = "Impl") public class SpringbootMongoDbApplication { public static void main(String[] args) { SpringApplication.run(SpringbootMongoDbApplication.class, args); } }
好开启一下mongodb服务,测试把
花了几天了解,希望包含