Mongodb java利用spring访问mongodb

1. 需要先外mongodb的配置文件修改下:

vi /etc/mongod.conf将bind_ip这一行去掉或改成客户端的ip,允许其他ip可以访问mongo

 

2.maven引入spring-data-mongodb包

 

3. 在spring的配置文件中增加以下内容:

 <mongo:mongo host="10.1.5.105" port="27017">
 </mongo:mongo>

 <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
  <constructor-arg ref="mongo" />
  <constructor-arg name="databaseName" value="mydb" />
 </bean>

 

4.这样便可以在application上下文中使用了:

@Controller
@RequestMapping("/MongoController")
public class MongoController {
 @Resource
 private MongoService mongoService;
 @Resource
 private MongoTemplate mongoTemplate;

 @RequestMapping(value = "index", method = RequestMethod.GET)
 public String index(HttpSession session, ModelMap model) {

  mongoTemplate.insert(new Person("2","kevin", 34));
  
  return "index";
 }
}

 

备注:

spring头部:

<?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:mvc="http://www.springframework.org/schema/mvc"

xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"

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-4.0.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-4.0.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

http://www.springframework.org/schema/data/mongo 

http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值