• SpringBoot集成mongodb


    SpringBoot集成mongodb

    1.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>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.1.1.RELEASE</version>
        </parent>
    
        <groupId>com.qy.learn.mongodb</groupId>
        <artifactId>learn-mongodb</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <maven.compiler.source>1.8</maven.compiler.source>
            <maven.compiler.target>1.8</maven.compiler.target>
            <maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>
            <maven.test.skip>true</maven.test.skip>
            <java.version>1.8</java.version>
            <spring.boot.version>2.0.1.RELEASE</spring.boot.version>
            <qy.code.version>0.0.1-SNAPSHOT</qy.code.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter</artifactId>
                <!-- 不使用springboot默认log -->
                <exclusions>
                    <exclusion>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-logging</artifactId>
                    </exclusion>
                </exclusions>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-log4j2</artifactId>
            </dependency>
    
            <!-- Spring Boot Web 依赖 -->
            <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>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-mongodb</artifactId>
            </dependency>
        </dependencies>
        <repositories>
            <repository>
                <id>nexus-aliyun</id>
                <name>Nexus aliyun</name>
                <url>http://maven.aliyun.com/nexus/content/groups/public</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </repository>
        </repositories>
        <pluginRepositories>
            <pluginRepository>
                <id>nexus-aliyun</id>
                <name>Nexus aliyun</name>
                <url>http://maven.aliyun.com/nexus/content/groups/public</url>
                <releases>
                    <enabled>true</enabled>
                </releases>
                <snapshots>
                    <enabled>false</enabled>
                </snapshots>
            </pluginRepository>
        </pluginRepositories>
    
    
        <build>
            <plugins>
                <!-- 要将源码放上去,需要加入这个插件 -->
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-source-plugin</artifactId>
                    <configuration>
                        <attach>true</attach>
                    </configuration>
                    <executions>
                        <execution>
                            <phase>compile</phase>
                            <goals>
                                <goal>jar</goal>
                            </goals>
                        </execution>
                    </executions>
                </plugin>
    
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>

    2.application.properties

    server.port=8088
      
    ## mongodb连接配置 配置
    spring.data.mongodb.host=192.168.159.129
    spring.data.mongodb.port=27017
    spring.data.mongodb.database=qydb

    3.log4j2.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!-- log4j2 本身日志打印级别,以及重新刷新配置文件的时间-->
    <Configuration status="WARN" monitorInterval="5">
        <Properties>
            <Property name="log-path">logs</Property>
            <Property name="log-file-temp">temp.log</Property>
            <Property name="log-file-info">info.log</Property>
            <Property name="log-file-warn">warn.log</Property>
            <Property name="log-file-error">error.log</Property>
            <!-- 输出格式 -->
            <!-- <Property name="pattern">%p [%date{yyyy-MM-dd HH:mm:ss,SSS}] [%thread] %l %m %n </Property> -->
            <Property name="pattern">%m %n </Property>
            <!-- 日志切割的最小单位 -->
            <property name="every_file_size">1M</property>
        </Properties>
        <Appenders>
            <!-- 重置太打印 打印debug及以上级别 -->
            <Console name="Console-Appender" target="SYSTEM_OUT">
                <ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY" />
                <PatternLayout pattern="${pattern}"/>
            </Console>
            
               <!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用-->
            <File name="RollingFile-Appender-Temp" fileName="${log-path}/${log-file-temp}" append="false">
                <PatternLayout pattern="${pattern}"/>
            </File> 
            <!-- 这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
            <RollingFile name="RollingFile-Appender-INFO" fileName="${log-path}/${log-file-info}" append="true"
                         filePattern="${log-path}/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
                <!-- 只输出INFO级别 -->
                <Filters>
                    <ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY" />
                    <ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL" />
                    <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL" />
                </Filters>
                <PatternLayout pattern="${pattern}" />
                <SizeBasedTriggeringPolicy size="${every_file_size}"/>
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了10 -->
                <DefaultRolloverStrategy max="10"/>
            </RollingFile>
            <RollingFile name="RollingFile-Appender-WARN" fileName="${log-path}/${log-file-warn}" append="true"
                         filePattern="${log-path}/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
                <!-- 只输出Warn级别 -->
                <Filters>
                    <ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY" />
                    <ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL" />
                </Filters>
                <PatternLayout pattern="${pattern}" />
                <SizeBasedTriggeringPolicy size="${every_file_size}"/>
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了10 -->
                <DefaultRolloverStrategy max="10"/>
            </RollingFile>
            <RollingFile name="RollingFile-Appender-ERROR" fileName="${log-path}/${log-file-error}" append="true"
                         filePattern="${log-path}/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
                <!-- 只输出ERROR级别 -->
                <Filters>
                    <ThresholdFilter level="ERROR" onMatch="ACCEPT" onMismatch="DENY" />
                </Filters>
                <PatternLayout pattern="${pattern}" />
                <SizeBasedTriggeringPolicy size="${every_file_size}"/>
                <!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了10 -->
                <DefaultRolloverStrategy max="10"/>
            </RollingFile>
        </Appenders>
        <Loggers>
            <logger name="java.sql" level="debug" additivity="false">
                <appender-ref ref="Console-Appender"/>
            </logger>
            <logger name="com.ibatis" level="debug" additivity="false">
                <appender-ref ref="Console-Appender"/>
            </logger>
            <!-- 第三方的软件日志级别 -->
            <logger name="org.springframework" level="info" additivity="true">
                <AppenderRef ref="RollingFile-Appender-WARN" />
                <AppenderRef ref="RollingFile-Appender-ERROR" />
            </logger>
            <!-- 第三方的软件日志级别 -->
            <logger name="org.apache" level="warn" additivity="true">
                <AppenderRef ref="RollingFile-Appender-WARN" />
                <AppenderRef ref="RollingFile-Appender-ERROR" />
            </logger>
            <!-- 异步输出 -->
            <Root level="INFO">
                <AppenderRef ref="Console-Appender"/>
                <AppenderRef ref="RollingFile-Appender-Temp"/>
                <AppenderRef ref="RollingFile-Appender-INFO" />
                <AppenderRef ref="RollingFile-Appender-WARN" />
                <AppenderRef ref="RollingFile-Appender-ERROR" />
            </Root>
        </Loggers>
    </Configuration>

    4.mongodb实体类

    package com.qy.learn.mongodb.manager;
    
    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;
    /**
     * @author 七脉
     * 描述:@Document定义mongodb集合,等于数据库表名称
     */
    @Document(collection="commodity")
    public class CommodityModel {
        
        /**
         * @Id声明主键字段,对应mongodb集合的_id属性,等于数据库主键
         */
        @Id
        private long commodityId;
        
        private String CommodityName;
        
        public CommodityModel() {
            super();
            // TODO Auto-generated constructor stub
        }
        
        public CommodityModel(long commodityId, String commodityName) {
            super();
            this.commodityId = commodityId;
            CommodityName = commodityName;
        }
    
        public long getCommodityId() {
            return commodityId;
        }
    
        public void setCommodityId(long commodityId) {
            this.commodityId = commodityId;
        }
    
        public String getCommodityName() {
            return CommodityName;
        }
    
        public void setCommodityName(String commodityName) {
            CommodityName = commodityName;
        }
        
    }

    5.启动类

    package com.qy.learn.mongodb;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    @SpringBootApplication
    public class MongodApplication {
        
        public static void main(String[] args) {
            SpringApplication.run(MongodApplication.class, args);
        }
        
    }

    6.单元测试

    package com.qy.learn.mongodb;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    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.test.context.junit4.SpringRunner;
    
    import com.qy.learn.mongodb.manager.CommodityModel;
    
    @SpringBootTest
    @RunWith(SpringRunner.class)
    public class MongodbTest {
        
        @Autowired
        private MongoTemplate mongoTemplate;
        
        @Test
        public void testInsert(){
            CommodityModel model = new CommodityModel(1l, "董志峰");
            mongoTemplate.insert(model);
        }
        
        @Test
        public void testUpdate(){
            Query query = new Query(Criteria.where("commodityId").is(1l));
            Update update = new Update();
            update.set("CommodityName", "董志峰2");
            mongoTemplate.updateMulti(query, update, CommodityModel.class);
        }
        
        @Test
        public void testRemove(){
            Query query = new Query(Criteria.where("commodityId").is(1l));
            mongoTemplate.remove(query,CommodityModel.class);
        }
        
        @Test
        public void testFind(){
            Query query = new Query(Criteria.where("commodityId").is(1l));
            CommodityModel model = mongoTemplate.findOne(query, CommodityModel.class);
            System.out.println(model.getCommodityId()+"-------"+model.getCommodityName());
        }
        
    }
  • 相关阅读:
    python第一个项目:爬取一个网站的所有图片
    python学习笔记(3)
    python学习笔记(3)
    python学习笔记(2)
    python学习笔记(2)
    机器学习入门(1)
    centos7安装google-chrome
    linux 系统监控命令之 top-(转自 Howie的专栏)
    linux 磁盘管理命令之df-(转自 Howie的专栏)
    sizeof()用法汇总-(转自风雷)
  • 原文地址:https://www.cnblogs.com/zwcry/p/10538090.html
Copyright © 2020-2023  润新知