博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMVC连接MongoDB操作数据库
阅读量:5892 次
发布时间:2019-06-19

本文共 5717 字,大约阅读时间需要 19 分钟。

ivy.xml

1、先引入以上的jar包:

2、使用MongoTemplate:

package com.d.service;import javax.servlet.http.HttpServletRequest;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;//@RestController//@RequestMapping("/test")public class TestService {    private static final Logger logger = LoggerFactory.getLogger(TestService.class);         @Autowired     MongoTemplate mongoTemplate;         @RequestMapping(value = "/check", method = RequestMethod.GET)    @ResponseBody    public JsonResult
check(HttpServletRequest request) { try { logger.info("Address:{}", request.getLocalAddr()); logger.info("Name:{}", request.getLocalName()); } catch (Throwable e) { logger.error(e.getMessage()); logger.debug(e.getMessage(), e); } return new JsonResult
("服务运行正常...").success(); } @RequestMapping(value = "/add", method = RequestMethod.GET) @ResponseBody public JsonResult
add(HttpServletRequest request) { try { TestMo mo = new TestMo(); mo.setId("1111"); mo.setMessage("2222"); mo.setName("3333"); mongoTemplate.insert(mo); } catch (Throwable e) { logger.error(e.getMessage()); logger.debug(e.getMessage(), e); return new JsonResult
(e.getMessage()).fail(0); } return new JsonResult
("服务运行正常...").success(); }}

3、使用Reosititory:

package com.repository;import org.springframework.data.mongodb.repository.MongoRepository;import com.model.MaterialInfo;public interface MaterialRepository extends MongoRepository
{}

Api:

package com.api;import javax.validation.Valid;import javax.ws.rs.DELETE;import javax.ws.rs.GET;import javax.ws.rs.POST;import javax.ws.rs.Path;import javax.ws.rs.QueryParam;import org.springframework.data.domain.Sort;import org.springframework.data.mongodb.core.query.Query;import com.model.MaterialInfo;import com.utils.QueryResult;public interface MaterialApi {    @POST    @Path("insert")    MaterialInfo insert(@Valid MaterialInfo materialInfo);        @DELETE    @Path("delete")    void delete(@QueryParam("id") String id);        @POST    @Path("update")    void update(@QueryParam("id") String id);        @POST    @Path("save")    MaterialInfo save(@Valid MaterialInfo materialInfo);    @GET    @Path("get")    MaterialInfo getBroadCastList(String id);    @POST    @Path("query/with/paging")    public QueryResult
queryWithPaging(Query query, Sort sort, // int start, int limit);}

Impl:

package com.api.impl;import javax.ws.rs.Path;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.data.domain.Sort;import org.springframework.data.mongodb.core.MongoTemplate;import org.springframework.data.mongodb.core.query.Query;import org.springframework.stereotype.Component;import com.api.MaterialApi;import com.model.MaterialInfo;import com.repository.MaterialRepository;import com.utils.QueryResult;@Path("/material")@Component("materialImpl")public class MaterialApiImpl implements MaterialApi {    @Autowired    private MaterialRepository _materialRepository;         @Autowired       @Qualifier("mongoTemplate")       MongoTemplate mongoTemplate;        @Override    public MaterialInfo insert(MaterialInfo materialInfo) {        // TODO Auto-generated method stub        return _materialRepository.insert(materialInfo);    }    @Override    public void delete(String id) {        // TODO Auto-generated method stub            }    @Override    public MaterialInfo save(MaterialInfo materialInfo) {        // TODO Auto-generated method stub        return null;    }    @Override    public MaterialInfo getBroadCastList(String id) {        // TODO Auto-generated method stub        return null;    }    @Override    public QueryResult
queryWithPaging(Query query, Sort sort, int start, int limit) { // TODO Auto-generated method stub return null; } @Override public void update(String id) { // TODO Auto-generated method stub }}

Service:

package com.service;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import com.api.MaterialApi;import com.model.MaterialInfo;@Component("materialService")public class MaterialService {    public static Logger logger = LoggerFactory.getLogger(MaterialService.class);        @Autowired    MaterialApi _materialApi;        public String save(MaterialInfo materialInfo){        try {             _materialApi.save(materialInfo);        } catch (Throwable e) {            return e.getMessage();        }        return "success";    }}

以上!

 缺少关键的beans.xml文件 补上去:注意其中的<mongo:repositories />很重要;

以上文件加载只能加载classpath下的文件,加载外部文件需修改配置如下: 
重点在添加file标识 mongodb.properties:
#mongodb mongodb.database=adbasemongodb.replicaSet=127.0.0.1:27017#mongodb.host=127.0.0.1#mongodb.port=27017

转载于:https://www.cnblogs.com/liangblog/p/7753756.html

你可能感兴趣的文章
java jni 原理_使用JNI技术实现Java和C++的交互
查看>>
java 重写system.out_重写System.out.println(String x)方法
查看>>
java 面向对象基本概念_Java面向对象-面向对象编程之基本概念
查看>>
java数值保留2位小数_java中如何使Double类型的数值保留两位小数问题
查看>>
php数组分行输出json_php数组输出这样的json
查看>>
Ubuntu 12.04安装
查看>>
mysql client命令行选项
查看>>
vc遍历网页表单并自动填写提交 .
查看>>
log4j
查看>>
自定义TabControl
查看>>
配置ORACLE 11g绿色版客户端和PLSQL远程连接环境
查看>>
wordpress wp_head()函数 浏览器顶部 空白28px 解决办法
查看>>
读书笔记:改变人心的技巧
查看>>
MATLAB实现频数表——hist的使用
查看>>
iphone 线程 NSCondition NSThread
查看>>
NSURLConnection下载文件并显示进度(HEAD)
查看>>
在Firefox中使用超级Bookmarklet
查看>>
Content type and column用法示例代码来自SharePoint会议
查看>>
设计模式:外观模式(Façade Pattern)
查看>>
ASP.NET中 DataList(数据列表)的使用前台绑定
查看>>