閱讀637 返回首頁    go 汽車大全


SpringBoot開發案例之整合mongoDB

springboot_mongodb

開始前,建議大家去了解以下文章,當然不看也沒問題:

MongoDB從入門到“精通”之簡介和如何安裝

MongoDB從入門到“精通”之如何優雅的安裝

MongoDB從入門到“精通”之整合JavaWeb項目

開發環境

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

項目結構

mongodb

相關配置

pom.xml:

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://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>https://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

注解說明

@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;

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

代碼:https://git.oschina.net/52itstyle/spring-boot-mongodb

作者: 小柒

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

本文版權歸作者和雲棲社區所有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁麵明顯位置給出, 如有問題, 可郵件(345849402@qq.com)谘詢。

最後更新:2017-07-19 20:03:16

  上一篇:go  5G即將到來 看物聯網的發展
  下一篇:go  測試