本地跑起来!IntellliJ IDEA+maven+spring+springMVC+tomcat+mongodb搭建本地开发环境

ThisLX 2020-02-15

在前面搭建的环境上加上mongodb配置文件,pom.xml增加mongo相关依赖,增加一些代码即可搭建成功。

1、增加mongdb-context.xml和mongodb.properties

mongdb-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mongo="http://www.springframework.org/schema/data/mongo"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/data/mongo
       http://www.springframework.org/schema/data/mongo/spring-mongo.xsd">
    <!--加载MongoDB属性配置文件-->
    <context:property-placeholder location="classpath*:mongodb.properties"/>
    <!--mongodb数据库配置-->
    <mongo:mongo-client replica-set="${mongo.host}" id="mongo">
        <mongo:client-options connections-per-host="${mongo.connectionsPerHost}"
                threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
                max-wait-time="${mongo.maxWaitTime}"
                socket-timeout="${mongo.socketTimeout}"
                connect-timeout="${mongo.connectTimeout}"/>
    </mongo:mongo-client>
    <!--工厂获取mongo实例-->
    <mongo:db-factory id="mongoDbFactory" dbname="ivydb" mongo-ref="mongo"/>
    <!--创建mongoTemplate-->
    <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
        <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
    </bean>
    <!--mongodb bean的仓库目录,会自动扫描扩展MongoRepository接口到接口进行注入-->
    <mongo:repositories base-package="com.example.ivy"/>
</beans>

mongodb.properties

#mongoDB连接配置
mongo.host=127.0.0.1:27017
mongo.connectionsPerHost=8
mongo.threadsAllowedToBlockForConnectionMultiplier=4
#连接超时时间
mongo.connectTimeout=1000
#等待时间
mongo.maxWaitTime=1500
#Socket超时时间
mongo.socketTimeout=1500

2、修改applicationContext.xml,增加mongodb相关配置

1     <!--引入MongoDB配置文件-->
2     <import resource="mongodb-context.xml"/>

3、在pom.xml文件中增加mongodb相关依赖

<dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-mongodb</artifactId>
          <version>2.0.1.RELEASE</version>
      </dependency>
        <dependency>
            <groupId>org.mongodb</groupId>
            <artifactId>mongo-java-driver</artifactId>
            <version>3.11.2</version>
        </dependency>

4、添加实体User

package com.example.ivy.entity;

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

@Document(collection = "user")
public class User {
    private int id;
    private String name;
    private String password;

    public User() {
    }

    public User(int id, String name, String password) {
        this.id = id;
        this.name = name;
        this.password = password;
    }


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

    public int getId() {
        return id;
    }

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

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name=‘" + name + ‘\‘‘ +
                ", password=‘" + password + ‘\‘‘ +
                ‘}‘;
    }
}

5、添加DAO

package com.example.ivy.dao.impl;

import com.example.ivy.entity.User;
import com.example.ivy.dao.IBaseDao;
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.Component;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service(value = "iBaseDaoImpl")
public class IBaseDaoImpl implements IBaseDao {
    //MongoTemplate是数据库和代码之间的接口,对数据库的操作都在它里面
    @Resource
    private MongoTemplate mongoTemplate;
    @Override
    public List<User> findAll() {
        return mongoTemplate.findAll(User.class,"user");
    }

    @Override
    public User findOne(int id) {
        Query query = new Query();
        Criteria criteria = Criteria.where("_id").is(id);
        query.addCriteria(criteria);
        return mongoTemplate.findOne(query,User.class);
    }

    @Override
    public void update(User user) {
        Update update = new Update();
        Query query = new Query();
        update.set("name", user.getName());
        update.set("password", user.getPassword());
        mongoTemplate.updateFirst(query.addCriteria(Criteria.where("_id").is(user.getId())), update, User.class);
    }

    @Override
    public void delete(int id) {
        mongoTemplate.remove(Query.query(Criteria.where("_id").is(id)), User.class);
    }

    @Override
    public void add(User user) {
        mongoTemplate.insert(user, "user");
    }

    @Override
    public void save(User user) {
        mongoTemplate.save(user);
    }
}

6、增加测试,查看环境是否搭建成功

package com.example.ivy.dao.impl;

import com.example.ivy.dao.IBaseDao;
import com.example.ivy.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({"classpath:applicationContext.xml","classpath:mongodb-context.xml"})
public class IBaseDaoImplTest {
    @Resource
    private IBaseDaoImpl baseDao ;

    @Test
    public void testMongo(){
        for (int i = 0; i < 10; i++) {
            User user = new User(i,"李丹" + i,"123");
            baseDao.save(user);
        }
    }

    @Test
    public void findAll() {
        List<User> users = new ArrayList<>();
        users = baseDao.findAll();
        for (User user :
                users) {
            System.out.println(user.toString());
        }
    }

    @Test
    public void findOne() {
        User user = new User();
        user = baseDao.findOne(2);
        System.out.println(user.toString());
    }

    @Test
    public void update() {
        User user = new User(7,"七宝","mamababa");
        baseDao.update(user);
        System.out.println(baseDao.findOne(7).toString());
    }

    @Test
    public void delete() {
        baseDao.delete(5);
        if (null == baseDao.findOne(5)){
            System.out.println("success");
        }
    }

    @Test
    public void add() {
        User user = new User(15,"ivy","ivy");
        baseDao.add(user);
        System.out.println(baseDao.findOne(15).toString());
    }


}

这些只是很简单的配置,可以有更高级更简洁的配置进行搭建。 

这个项目可以完全在本地跑起来,不需要该任何配置。

项目完整代码:https://github.com/Ivyvivid/springmvc-mongo 

相关推荐