SpringBoot开发案例之整合mongoDB

mongodb.jpg

开始前,建议大家去了解以下文章,当然不看也没问题:

MongoDB从入门到“精通”之简介和如何安装

MongoDB从入门到“精通”之如何优雅的安装

MongoDB从入门到“精通”之整合JavaWeb项目

开发环境

JDK1.7、Maven、Eclipse、SpringBoot1.5.2、mongodb3.4,Robomongo(可视化工具)

项目结构

mongodb.png

相关配置

pom.xml:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.itstyle.mongodb</groupId>
  <artifactId>spring-boot-mongodb</artifactId>
  <packaging>jar</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>spring-boot-mongodb</name>
  <url>http://maven.apache.org</url>
  
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.7</java.version>
  </properties>
  
  <!-- spring-boot-starter-parent包含了大量配置好的依赖管理,在自己项目添加这些依赖的时候不需要写<version>版本号 -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.2.RELEASE</version>
    <relativePath/>
  </parent>
  <!-- 配置依赖 -->
  <dependencies>
        <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-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-mongodb</artifactId>
        </dependency>
  </dependencies>
  <build>
        <plugins>
            <!-- 打包项目 mvn clean package -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <dependencies>
                    <!-- mvn spring-boot:run 热部署启动 -->
                    <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>springloaded</artifactId>
                        <version>1.4.0.RELEASE</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>
</project>

实体类 Users.java:

package com.itstyle.mongodb.model;

import java.io.Serializable;

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.Document;

@Document(collection="users")
@CompoundIndexes({
    @CompoundIndex(name = "age_idx", def = "{'name': 1, 'age': -1}")
})
public class Users  implements Serializable{
    private static final long serialVersionUID = 1L;
    @Indexed
    private String uid;
    private String name;
    private int age;
    @Transient
    private String address;
   
    public Users(String uid, String name, int age) {
        super();
        this.uid = uid;
        this.name = name;
        this.age = age;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return String.format(
                "Customer[name='%s', age='%s']",
                 name, age);
    }
}

业务接口 IUserService.java:

package com.itstyle.mongodb.service;

import java.util.List;

import com.itstyle.mongodb.model.Users;
/**
 * mongodb 案例
 * 创建者  小柒
 * 创建时间    2017年7月19日
 *
 */
public interface IUserService {
    public void saveUser(Users users);

    public Users findUserByName(String name);

    public void removeUser(String name);

    public void updateUser(String name, String key, String value);

    public List<Users> listUser();
}

业务实现UserServiceImpl.java:

package com.itstyle.mongodb.service.impl;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
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 com.itstyle.mongodb.model.Users;
import com.itstyle.mongodb.service.IUserService;

@Component("userService")
public class UserServiceImpl implements IUserService {
    @Autowired
    MongoOperations mongoTemplate;

    public void saveUser(Users users) {
        mongoTemplate.save(users);
    }

    public Users findUserByName(String name) {
        return mongoTemplate.findOne(
                new Query(Criteria.where("name").is(name)), Users.class);
    }

    public void removeUser(String name) {
        mongoTemplate.remove(new Query(Criteria.where("name").is(name)),
                Users.class);
    }

    public void updateUser(String name, String key, String value) {
        mongoTemplate.updateFirst(new Query(Criteria.where("name").is(name)),
                Update.update(key, value), Users.class);

    }

    public List<Users> listUser() {
        return mongoTemplate.findAll(Users.class);
    }
}

启动类Application.java:

package com.itstyle.mongodb;

import org.apache.log4j.Logger;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.ComponentScan;
@EnableAutoConfiguration
@ComponentScan(basePackages={"com.itstyle.mongodb"})
public class Application  {
    private static final Logger logger = Logger.getLogger(Application.class);
    
    public static void main(String[] args) throws InterruptedException {
        SpringApplication.run(Application.class, args);
        logger.info("项目启动 ");
    }
}

基础配置application.properties:

# 项目contextPath,一般在正式发布版本中
server.context-path=/mongodb
# 服务端口
server.port=8080
# session最大超时时间(分钟),默认为30
server.session-timeout=60
# 该服务绑定IP地址,启动服务器时如本机不是该IP地址则抛出异常启动失败,只有特殊需求的情况下才配置
# server.address=192.168.16.11
# tomcat最大线程数,默认为200
server.tomcat.max-threads=800
# tomcat的URI编码
server.tomcat.uri-encoding=UTF-8

#mongo2.x支持以上两种配置方式 mongo3.x仅支持uri方式
#mongodb note:mongo3.x will not use host and port,only use uri
#spring.data.mongodb.host=192.168.1.180
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=itstyle
#没有设置密码
#spring.data.mongodb.uri=mongodb://192.168.1.180:27017/itstyle
#设置了密码
spring.data.mongodb.uri=mongodb://itstyle:itstyle@192.168.1.180:27017/itstyle

测试类SpringbootMongodbApplication.java:

package com.itstyle.mongodb.test;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

import com.itstyle.mongodb.model.Users;
import com.itstyle.mongodb.service.IUserService;

@SpringBootApplication
@ComponentScan(basePackages={"com.itstyle.mongodb"})
public class SpringbootMongodbApplication implements CommandLineRunner {

    @Autowired
    private IUserService userService;

    public static void main(String[] args) {
        SpringApplication.run(SpringbootMongodbApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        try {
            Users users = new Users("1", "小明", 10);
            users.setAddress("青岛市");
            userService.saveUser(users);
            List<Users> list = userService.listUser();
            System.out.println("一共这么多人:"+list.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

最后,运行测试类,使用可视化工具Robomongo查看:

keshihua.png

注解说明

@Document

标注在实体类上,与hibernate异曲同工。

@Document(collection="users")
public class Users  implements Serializable{
    private static final long serialVersionUID = 1L;
    ...省略代码

@CompoundIndex

复合索引,加复合索引后通过复合索引字段查询将大大提高速度。

@Document(collection="users")
@CompoundIndexes({
    @CompoundIndex(name = "age_idx", def = "{'name': 1, 'age': -1}")
})
public class Users  implements Serializable{
    private static final long serialVersionUID = 1L;
    ...省略代码

@Id

MongoDB默认会为每个document生成一个 _id 属性,作为默认主键,且默认值为ObjectId,可以更改 _id 的值(可为空字符串),但每个document必须拥有 _id 属性。
当然,也可以自己设置@Id主键,不过官方建议使用MongoDB自动生成。

@Indexed

声明该字段需要加索引,加索引后以该字段为条件检索将大大提高速度。
唯一索引的话是@Indexed(unique = true)。
也可以对数组进行索引,如果被索引的列是数组时,mongodb会索引这个数组中的每一个元素。

@Indexed
private String uid;

@Transient

被该注解标注的,将不会被录入到数据库中。只作为普通的javaBean属性。

@Transient
private String address;

@Field

代表一个字段,可以不加,不加的话默认以参数名为列名。

@Field("firstName")
private String name;

当然了,以上的以上,可能仅仅是冰山一角,还有很多特性等待大家去挖掘。

代码:http://git.oschina.net/52itstyle/spring-boot-mongodb

qrcode_for_gh_bf7a27ade681_258.jpg

作者: 小柒

出处: https://blog.52itstyle.com

分享是快乐的,也见证了个人成长历程,文章大多都是工作经验总结以及平时学习积累,基于自身认知不足之处在所难免,也请大家指正,共同进步。

本文版权归作者所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出, 如有问题, 可邮件(345849402@qq.com)咨询。