Java操作MongoDB的增删改查,完整项目分享

x33g5p2x  于2021-12-30 转载在 Go  
字(6.3k)|赞(0)|评价(0)|浏览(405)

使用idea,创建SpringBoot项目,详细介绍Java操作MongoDB的增删改查全过程。

1.安装MongoDB

这里略,详情请参考《window安装MongoDB详解》博客

2.idea创建SpringBoot项目

这里略,详情请参考《idea中基于MongoDB,创建SpringBoot项目》博客

3.idea连接MongoDB

这里略,详情请参考《idea安装Mongo Plugin插件,连接MongoDB_一火的专栏-CSDN博客》博客

4.编写代码

4.1连接MongoDB配置文件

spring.data.mongodb.host=127.0.0.1
spring.data.mongodb.port=27017
spring.data.mongodb.database=user

4.2实体代码

import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;

/**
 * 实体层
 */
@Document(collection="user")
public class User {

    @Id // 指定ID
    private String id;

    @Field("name") // 指定域名,覆盖默认
    private String name;

    @Field("password") // 指定域名,覆盖默认
    private String password;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

4.3dao代码

@Service
public class UserDao {
    @Autowired
    private MongoTemplate mongoTemplate;
    public User save(User user) {
        mongoTemplate.insert(user);
        return user;
    }
    public User getById(String id) {
        return mongoTemplate.findById(id, User.class);
    }
    public User deleteById(String id) {
        User user = mongoTemplate.findById(id, User.class);
        mongoTemplate.remove(user);
        return user;
    }

    public User update(User user) {
        mongoTemplate.save(user);
        return user;
    }

    public List<User> getAllUsers() {
        return mongoTemplate.findAll(User.class);
    }

    public Map<String, Object> query(String userName,  int page,  int size) {

        // 条件
        Criteria criteria1 = Criteria.where("name").is(userName);
        Query query = new Query();
        if (userName!= null) {
            query.addCriteria(criteria1);
        }

        // 数量
        long total = mongoTemplate.count(query, User.class);

        // 分页
        query.skip((page - 1) * size).limit(size);

        List<User> data = mongoTemplate.find(query, User.class);
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("data", data);
        map.put("total", total);

        return map;
    }


}

4.4service代码

@Service
public class UserService {
    @Autowired
    private UserDao userDao;
    public User save(User user) {
        return userDao.save(user);
    }
    public User getById(String id) {
        return userDao.getById(id);
    }
    public User deleteById(String id) {
        return userDao.deleteById(id);
    }

    public User update(User user) {
        return userDao.update(user);
    }

    public List<User> getAllUsers() {
        return userDao.getAllUsers();
    }

    public Map<String, Object> query(String userName, int page, int size) {
        return userDao.query(userName,page,size);
    }
}

4.5controller代码

@RestController
@RequestMapping("/user")
@EnableSwagger2
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 增加
     * @param user
     * @return
     */
    @PostMapping("/insert")
    @ApiOperation (value = "insert",notes = "插入")
    public User insertUser(User user) {
        return userService.save(user);
    }

    /**
     * 查询
     * @param id
     * @return
     */
    @GetMapping("/get/{id}")
    @ApiOperation (value = "get",notes = "查询")
    public User getUserById(@PathVariable String id) {
        return userService.getById(id);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    @ApiOperation (value = "delete",notes = "删除")
    public User deleteUserById(@PathVariable String id) {
        return userService.deleteById(id);
    }

    /**
     * 修改
     * @param user
     * @return
     */
    @PutMapping("/update")
    @ApiOperation (value = "update",notes = "修改")
    public User updateUser(User user) {
        return userService.update(user);
    }

    /**
     * 查询所有的用户
     * @return
     */
    @GetMapping("/get/all")
    @ApiOperation (value = "getAll",notes = "获取所有")
    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    /**
     * 分页查询用户
     * @param userName
     * @param page
     * @param size
     * @return
     */
    @GetMapping("/select/{page}/{size}")
    @ApiOperation (value = "select",notes = "分页查询")
    public Map<String, Object> selectUserByProperty(String userName, @PathVariable int page, @PathVariable int size) {
        return userService.query(userName,page,size);
    }
}

4.6pom.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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.5.6</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>mongodb</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>mongodb</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger2</artifactId>
			<version>2.9.2</version>
		</dependency>
		<!-- 接口API生成html文档 -->
		<dependency>
			<groupId>io.springfox</groupId>
			<artifactId>springfox-swagger-ui</artifactId>
			<version>2.6.1</version>
		</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-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>5.3.14</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>5.3.14</version>
		</dependency>
		
		
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

5.代码接口测试

访问​​​​​​http://localhost:8080/swagger-ui.html出现如下界面:


 下面使用新增接口举例说明,其他接口类似


 

完整项目地址 www.zrscsoft.com/sitepic/12146.html

相关文章