mongodb与spring mvc 整合
1.pom文件添加对mongodb的倚赖
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.2.2</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>${data.mongodb}</version>
</dependency> <dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-cross-store</artifactId>
<version>${data.mongodb}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb-log4j</artifactId>
<version>${data.mongodb}</version>
</dependency>
2.applicationContext.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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- 扫描 -->
<context:component-scan base-package="cn.com.xxx.mongodb"/> <!-- 引入mongodb的相关配置 -->
<import resource="classpath:spring-mongodb.xml"/> </beans>
4.mongodb.properties
#数据库名称
mongo.dbname = test
#用户名
mongo.username = root
mongo.credentials=root:000000@test
#密码
mongo.password = 000000
#主机
mongo.host = 127.0.0.1
#端口号
mongo.port= 27017
#一个线程变为可用的最大阻塞数
mongo.connectionsPerHost= 8
#线程队列数,它以上面connectionsPerHost值相乘的结果就是线程队列最大值
mongo.threadsAllowedToBlockForConnectionMultiplier= 4
#连接超时时间(毫秒)
mongo.connectTimeout= 1500
#最大等待时间
mongo.maxWaitTime= 1500
#自动重连
mongo.autoConnectRetry= true
#scoket保持活动
mongo.socketKeepAlive= true
#scoket超时时间
mongo.socketTimeout=1500
#读写分离
mongo.slaveOk=true
3.spring-mongodb.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"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- 加载mongodb的属性配置文件 -->
<context:property-placeholder location="classpath:mongodb.properties" /> <!-- 定义mongo对象,对应的是mongodb官方jar包中的Mongo,replica-set设置集群副本的ip地址和端口 -->
<!--
<mongo:mongo id="mongo" host="${mongo.host}" port="${mongo.port}" > <mongo:client-options
connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
auto-connect-retry="${mongo.autoConnectRetry}"
socket-keep-alive="${mongo.socketKeepAlive}"
socket-timeout="${mongo.socketTimeout}"
slave-ok="${mongo.slaveOk}"
write-number="1"
write-timeout="0"
write-fsync="true"/>
</mongo:mongo>
-->
<!-- 我们使用的mongodb的版本是3.X,所以在构造这段话的时候要根据 Mongo 类的构造函数来构造,不同版本可能会造成构造函数的不同-->
<mongo:mongo-client id="mongo" host="${mongo.host}" port="${mongo.port}" credentials="${mongo.credentials}"> <mongo:client-options
connections-per-host="${mongo.connectionsPerHost}"
threads-allowed-to-block-for-connection-multiplier="${mongo.threadsAllowedToBlockForConnectionMultiplier}"
connect-timeout="${mongo.connectTimeout}"
max-wait-time="${mongo.maxWaitTime}"
socket-keep-alive="${mongo.socketKeepAlive}"
socket-timeout="${mongo.socketTimeout}"
/>
</mongo:mongo-client> <!-- 用户验证 -->
<bean id="userCredentials" class="org.springframework.data.authentication.UserCredentials">
<constructor-arg name="username" value="${mongo.username}" />
<constructor-arg name="password" value="${mongo.password}" />
</bean>
<!-- mongo的工厂,通过它来取得mongo实例,dbname为mongodb的数据库名,没有的话会自动创建 -->
<bean id="mongoDbFactory"
class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
<constructor-arg ref="mongo" />
<constructor-arg value="${mongo.dbname}" />
<!-- <constructor-arg ref="userCredentials" /> -->
</bean> <bean id="mappingContext"
class="org.springframework.data.mongodb.core.mapping.MongoMappingContext" /> <bean id="defaultMongoTypeMapper"
class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
<constructor-arg name="typeKey">
<null />
</constructor-arg>
</bean> <!-- collection的映射 -->
<bean id="mappingMongoConverter"
class="org.springframework.data.mongodb.core.convert.MappingMongoConverter">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mappingContext" ref="mappingContext" />
<property name="typeMapper" ref="defaultMongoTypeMapper" />
</bean> <!-- mongodb的主要操作对象,所有对mongodb的增删改查的操作都是通过它完成 -->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
<constructor-arg name="mongoConverter" ref="mappingMongoConverter" />
</bean>
<bean id="audience" class="cn.com.xxx.mongodb.aop.Audience"/> <aop:config proxy-target-class="true">
<aop:aspect ref="audience">
<aop:pointcut id="performance" expression="execution(* cn.com.mongodb.service.impl.*.*(..))"/> <aop:before pointcut-ref="performance" method="takeSeats"/>
<aop:before pointcut-ref="performance" method="turnOffCellPhones"/>
<aop:around pointcut-ref="performance" method="around"/>
<aop:after-returning pointcut-ref="performance" method="applaud"/>
<aop:after-throwing pointcut-ref="performance" method="demandRefund"/>
<aop:after pointcut-ref="performance" method="after"/>
</aop:aspect>
</aop:config>
</beans>
5.为了使javabean对象与mongodb对象相互转化,本人借鉴别人的例子,稍加改动, 主要是应对数据库表字段的命名是含 _ 的这种方式,首先需要约定在生成java pojo的时候,每个字段上面要加上@Field注解(方便利用反射来让两者之间相互转换)
@Document(collection="item_info")
public class ItemInfo implements Serializable { private static final long serialVersionUID = 1L;
private Oid _id;
@Field(value="item_id")
private String itemId;
@Field(value="item_name")
private String itemName;
@Field(value="price")
private Double price;
@Field(value="desc")
private String desc; public Oid get_id() {
return _id;
} public void set_id(Oid _id) {
this._id = _id;
} public String getItemId() {
return itemId;
} public void setItemId(String itemId) {
this.itemId = itemId;
} public String getItemName() {
return itemName;
} public void setItemName(String itemName) {
this.itemName = itemName;
} public Double getPrice() {
return price;
} public void setPrice(Double price) {
this.price = price;
} public String getDesc() {
return desc;
} public void setDesc(String desc) {
this.desc = desc;
} @Override
public String toString() {
return "ItemInfo [_id=" + _id + ", itemId=" + itemId + ", itemName="
+ itemName + ", price=" + price + ", desc=" + desc + "]";
}
实现java对象与DBObject对象之间的相互转化
public class BeanUtil { /**
* 把实体bean对象转换成DBObject
* @param bean
* @return
* @throws IllegalArgumentException
* @throws IllegalAccessException
*/
public static <T> DBObject bean2DBObject(T bean) throws IllegalArgumentException,
IllegalAccessException {
if (bean == null) {
return null;
}
DBObject dbObject = new BasicDBObject();
// 获取对象对应类中的所有属性域
Field[] fields = bean.getClass().getDeclaredFields(); // 获取所有注解
for (Field field : fields) {
org.springframework.data.mongodb.core.mapping.Field anno = field.getAnnotation(org.springframework.data.mongodb.core.mapping.Field.class);
// 获取属性名
String varName = field.getName(); if("serialVersionUID".equals(varName) || "_id".equals(varName)){
continue;
} // 获取注解的值
varName = anno.value();
// 修改访问控制权限
boolean accessFlag = field.isAccessible();
if (!accessFlag) {
field.setAccessible(true);
}
Object param = field.get(bean);
if (param == null) {
continue;
} else if (param instanceof Integer) {//判断变量的类型
int value = ((Integer) param).intValue();
dbObject.put(varName, value);
} else if (param instanceof String) {
String value = (String) param;
dbObject.put(varName, value);
} else if (param instanceof Double) {
double value = ((Double) param).doubleValue();
dbObject.put(varName, value);
} else if (param instanceof Float) {
float value = ((Float) param).floatValue();
dbObject.put(varName, value);
} else if (param instanceof Long) {
long value = ((Long) param).longValue();
dbObject.put(varName, value);
} else if (param instanceof Boolean) {
boolean value = ((Boolean) param).booleanValue();
dbObject.put(varName, value);
} else if (param instanceof Date) {
Date value = (Date) param;
dbObject.put(varName, value);
}
// 恢复访问控制权限
field.setAccessible(accessFlag);
} return dbObject;
} /**
* 把DBObject转换成bean对象
* @param dbObject
* @param bean
* @return
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws NoSuchMethodException
*/
public static <T> T dbObject2Bean(DBObject dbObject, T bean) throws IllegalAccessException,
InvocationTargetException, NoSuchMethodException {
if (bean == null) {
return null;
}
Field[] fields = bean.getClass().getDeclaredFields();
for (Field field : fields) {
String varName = field.getName();
org.springframework.data.mongodb.core.mapping.Field anno = field.getAnnotation(org.springframework.data.mongodb.core.mapping.Field.class);
if("serialVersionUID".equals(varName) || "_id".equals(varName)){
continue;
} String fieldName = anno.value();
Object object = dbObject.get(fieldName);
if (object != null) {
BeanUtils.setProperty(bean, varName, object);
}
}
return bean;
}
}
好了,准备工作就做好了
相应的Service与实现方法
public interface ItemInfoService { // 查询
public List<ItemInfo> getItemInfo(JSONObject json) throws Exception; // 保存
public int save(ItemInfo itemInfo) throws Exception; // 更新
public void update(ItemInfo intemInfo) throws Exception;
}
@Service(value="itemInfoService")
public class ItemInfoServiceImpl implements ItemInfoService { @Autowired
private MongoTemplate mongoTemplate;
private final static String COLLECTION_NAME = "item_info"; @Override
@SuppressWarnings("static-access")
public List<ItemInfo> getItemInfo(JSONObject json) throws Exception{
List<ItemInfo> list = new ArrayList<ItemInfo>();
// 判断查询的json中传递过来的参数
DBObject query = new BasicDBObject();
// item_id,item_name,price,desc
if(json.has("item_id")){ query.put("item_id", json.getString("item_id"));
}else if(json.has("item_name")){
query.put("item_name", json.getString("item_name"));
} DBCursor results = mongoTemplate.getCollection("item_info").find(query);
if(null != results){
Iterator<DBObject> iterator = results.iterator();
while(iterator.hasNext()){
//Document doc = (Document) iterator.next();
BasicDBObject obj = (BasicDBObject) iterator.next();
//System.out.println(obj.toJson());
// json 字符串
String objStr = obj.toString();
//JSONObject itemInfoJson = new JSONObject().fromObject(objStr);
//itemInfoJson.put("_id", itemInfoJson.getJSONObject("_id").getString("$oid"));
ItemInfo itemInfo = new ItemInfo();
itemInfo = BeanUtil.dbObject2Bean(obj, itemInfo);
list.add(itemInfo);
}
} return list;
} @Override
public int save(ItemInfo itemInfo) throws Exception {
itemInfo.setDesc("1111");
itemInfo.setItemId("i1234567890123");
itemInfo.setItemName("item_name_xx");
itemInfo.setPrice(110.0); DBCollection collection = this.mongoTemplate.getCollection("item_info");
int result = 0;
DBObject iteminfoObj = BeanUtil.bean2DBObject(itemInfo); //iteminfoObj.removeField("serialVersionUID");
//result = collection.insert(iteminfoObj).getN();
WriteResult writeResult = collection.save(iteminfoObj);
result = writeResult.getN();
return result;
} @Override
public void update(ItemInfo intemInfo) throws Exception { DBCollection collection = this.mongoTemplate.getCollection(COLLECTION_NAME);
ItemInfo queryItemInfo = new ItemInfo();
queryItemInfo.setItemId(intemInfo.getItemId());
DBObject itemInfoObj = BeanUtil.bean2DBObject(intemInfo);
DBObject query = BeanUtil.bean2DBObject(queryItemInfo);
collection.update(query, itemInfoObj);
} }
junit test
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:applicationContext.xml")
public class ItemInfoServiceTest { @Autowired
private ItemInfoService itemInfoService; @Ignore
@Test
public void testSave(){
ItemInfo itemInfo = new ItemInfo();
try {
this.itemInfoService.save(itemInfo);
} catch (Exception e) {
e.printStackTrace();
}
} @Ignore
@Test
public void testGetItemInfo(){
List<ItemInfo> list = new ArrayList<ItemInfo>();
JSONObject json = new JSONObject();
//json.put("item_id", "47a09d51-bf24-442b-9076-4701dcb614b9");
json.put("item_id", "i1234567890123");
try {
list = this.itemInfoService.getItemInfo(json);
if(null != list && list.size() > 0){
//System.out.println(list.get(0).toString());
for (ItemInfo itemInfo : list) {
//itemInfo.setItemName("======");
this.itemInfoService.getItemInfo(json);
}
}
System.out.println(1 / 0);
} catch (Exception e) {
e.printStackTrace();
}
} @Test
public void testUpdate(){
JSONObject json = new JSONObject();
//json.put("item_id", "47a09d51-bf24-442b-9076-4701dcb614b9");
json.put("item_id", "i1234567890123");
List<ItemInfo> list = new ArrayList<ItemInfo>();
try {
list = this.itemInfoService.getItemInfo(json); if(null != list && list.size() > 0){
for (ItemInfo itemInfo : list) { }
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
OK , 测试完成。
mongodb与spring mvc 整合的更多相关文章
- spring MVC 整合mongodb
Spring Mongodb 目录 1 SPRING整合MONGODB 1 1.1 环境准备 1 1.2 包依赖 1 1.3 配置 2 2 案列 5 2.1 SPRING MVC整合MONGODB代码 ...
- Spring与Struts2整合VS Spring与Spring MVC整合
Spring与Struts2整合,struts.xml在src目录下 1.在web.xml配置监听器 web.xml <!-- 配置Spring的用于初始化ApplicationContext的 ...
- MyBatis+Spring+Spring MVC整合开发
MyBatis+Spring+Spring MVC整合开发课程观看地址:http://www.xuetuwuyou.com/course/65课程出自学途无忧网:http://www.xuetuwuy ...
- 【RabbitMQ系列】 Spring mvc整合RabbitMQ
一.linux下安装rabbitmq 1.安装erlang环境 wget http://erlang.org/download/otp_src_18.2.1.tar.gz tar xvfz otp_s ...
- Java基础-SSM之Spring和Mybatis以及Spring MVC整合案例
Java基础-SSM之Spring和Mybatis以及Spring MVC整合案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 能看到这篇文章的小伙伴,详细你已经有一定的Java ...
- spring mvc整合mybaitis和log4j
在上一篇博客中,我介绍了在mac os上用idea搭建spring mvc的maven工程,但是一个完整的项目肯定需要数据库和日志管理,下面我就介绍下spring mvc整合mybatis和log4j ...
- Spring MVC 整合Swagger的一些问题总结
在做Spring MVC 整合swagger的时候,遇到的两个问题: 第一个问题 在网上找了一些Spring MVC 和Swagger的例子,照着一步步的配置,结果,到最后,项目都起来了,没有任何问题 ...
- 【Java Web开发学习】Spring MVC整合WebSocket通信
Spring MVC整合WebSocket通信 目录 ========================================================================= ...
- MQTT 3 ——MQTT与Spring Mvc整合
本篇记录一下MQTT客户端与Spring Mvc整合 网络上已经有很多的MQTT客户端与SpringBoot整合的技术文档,但是与Spring Mvc框架的整合文档似乎并不太多,可能是因为Spri ...
随机推荐
- tomcat服务器怎样远程调试
适合windows系统 1.首先tomcat/bin目录下startup.bat打开最前面添加以下代码: SET CATALINA_OPTS=-server -Xdebug -Xnoagent -Dj ...
- 解决Mac系统升级导致cocoapods失效问题
使用pod install出现如下错误 -bash: /usr/local/bin/pod: /System/Library/Frameworks/Ruby.framework/Versions/2. ...
- 升讯威微信营销系统开发实践:所见即所得的微官网( 完整开源于 Github)
GitHub:https://github.com/iccb1013/Sheng.WeixinConstruction因为个人精力时间有限,不会再对现有代码进行更新维护,不过微信接口比较稳定,经测试至 ...
- 吴恩达机器学习笔记36-正则化和偏差/方差(Regularization and Bias_Variance)
在我们在训练模型的过程中,一般会使用一些正则化方法来防止过拟合.但是我们可能会正则化的程度太高或太小了,即我们在选择λ 的值时也需要思考与刚才选择多项式模型次数类似的问题. 我们选择一系列的想要测试的
- Go语言复制文件
需要使用io包的Copy方法 package main import ( "fmt" "io" "os" ) //自己编写一个函数,接收两个 ...
- python之N阶乘结果末尾有几个0
算法思路:首先是算阶乘,可以使用内置函数reduce实现,其次是计算结果的末尾有几个0,可以使用除余判断 代码如下: #!/usr/bin/env python#-*-coding:utf-8-*- ...
- html标签详解(2)
http标签详解 声明 1:这里的文字都是我从我自己csdn账号拷贝过来,是本人学习总结的结晶,所以请尊重本作品.2:如要要转载本文章,则要说明文字的出处.3:如有哪里不对欢迎指出. 在上一篇文章中主 ...
- ASP.NET Core身份认证服务框架IdentityServer4(2)-整体介绍
一.整体情况 现代应用程序看起来更像这个: 最常见的相互作用: 浏览器与Web应用程序的通信 Browser -> Web App Web应用程序与Web API通信 基于浏览器的应用程序与We ...
- sql server 备份与恢复系列一 必备知识
一.备份概述 数据安全是数据库的生命,数据库在使用过程中难免会遇到如:使用者的误操作或是被恶意修改,硬件故障导致数据文件无法被访问,自然灾害导致机房在物理上的损毁.本章从备份与恢复的功能作为解决问题的 ...
- mysql 开发进阶篇系列 4 SQL 优化(各种优化方法点)
1 通过handler_read 查看索引使用情况 如果索引经常被用到 那么handler_read_key的值将很高,这个值代表了一个行被索引值读的次数, 很低的值表明增加索引得到的性能改善不高,索 ...