spring mvc 集成mongoDB项目 例子

免费下载项目:点击打开链接

这个pom内容有点多,有的可以不用

<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/maven-v4_0_0.xsd">

	<modelVersion>4.0.0</modelVersion>
	<groupId>org.rui.mong</groupId>
	<artifactId>mongos</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>mongos Maven Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<org.springframework-version>4.0.6.RELEASE</org.springframework-version>
		<org.hibernate-version>4.3.1.Final</org.hibernate-version>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<!-- 依赖 管理 -->
	<dependencies>
		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-mongodb</artifactId>
			<version>1.4.1.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.data</groupId>
			<artifactId>spring-data-commons-core</artifactId>
			<version>1.4.1.RELEASE</version>
		</dependency>

<!-- 		<dependency> -->
<!-- 			<groupId>org.springframework.data</groupId> -->
<!-- 			<artifactId>spring-data-mongodb</artifactId> -->
<!-- 			<version>1.5.4.RELEASE</version> -->
<!-- 		</dependency> -->

			<!-- spring jar -->
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-core</artifactId>
				<version>${org.springframework-version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-context</artifactId>
				<version>${org.springframework-version}</version>
				<!-- Exclude Commons Logging in favor of SLF4j -->
				<exclusions>
					<exclusion>
						<groupId>commons-logging</groupId>
						<artifactId>commons-logging</artifactId>
					</exclusion>
				</exclusions>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-context-support</artifactId>
				<version>${org.springframework-version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-test</artifactId>
				<version>${org.springframework-version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-aop</artifactId>
				<version>${org.springframework-version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-beans</artifactId>
				<version>${org.springframework-version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-orm</artifactId>
				<version>${org.springframework-version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-aspects</artifactId>
				<version>${org.springframework-version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-webmvc</artifactId>
				<version>${org.springframework-version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-tx</artifactId>
				<version>${org.springframework-version}</version>
			</dependency>

			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-web</artifactId>
				<version>${org.springframework-version}</version>
			</dependency>

			<!-- hiberante 4 -->
			<dependency>
				<groupId>org.hibernate</groupId>
				<artifactId>hibernate-core</artifactId>
				<version>${org.hibernate-version}</version>
			</dependency>

			<dependency>
				<groupId>org.hibernate</groupId>
				<artifactId>hibernate-validator</artifactId>
				<version>${org.hibernate-version}</version>
			</dependency>

			<dependency>
				<groupId>javax.validation</groupId>
				<artifactId>validation-api</artifactId>
				<version>1.0.0.GA</version>
				<scope>provided</scope>
			</dependency>

			<!--enable hibernate to use its proxy model -->
			<!-- <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId>
				<version>3.18.1-GA</version> </dependency> -->
			<!-- jpa 注解 -->
			<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>ejb3-persistence</artifactId>
				<version>3.3.2.Beta1</version> </dependency> -->

			<dependency>
				<groupId>org.hibernate</groupId>
				<artifactId>hibernate-entitymanager</artifactId>
				<version>${org.hibernate-version}</version>
			</dependency>

			<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-annotations</artifactId>
				<version>3.5.6-Final</version> </dependency> -->
			<!-- <version>3.4.0.GA</version> -->

			<dependency>
				<groupId>org.apache.commons</groupId>
				<artifactId>commons-dbcp2</artifactId>
				<version>2.0.1</version>
			</dependency>

			<dependency>
				<groupId>org.slf4j</groupId>
				<artifactId>slf4j-log4j12</artifactId>
				<version>1.6.1</version>
			</dependency>

			<!-- <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-core</artifactId>
				<version>2.0.2</version> </dependency> -->

			<dependency>
				<groupId>log4j</groupId>
				<artifactId>log4j</artifactId>
				<version>1.2.17</version>
			</dependency>

			<dependency>
				<groupId>mysql</groupId>
				<artifactId>mysql-connector-java</artifactId>
				<version>5.1.6</version>
			</dependency>

			<dependency>
				<groupId>junit</groupId>
				<artifactId>junit</artifactId>
				<version>4.11</version>
				<scope>test</scope>
			</dependency>

			<dependency>
				<groupId>com.google.code.gson</groupId>
				<artifactId>gson</artifactId>
				<version>2.2.4</version>
			</dependency>

			<dependency>
				<groupId>javax.servlet</groupId>
				<artifactId>javax.servlet-api</artifactId>
				<version>3.0.1</version>
				<scope>provided</scope>
			</dependency>

			<!-- jackson -->
			<dependency>
				<groupId>com.fasterxml.jackson.core</groupId>
				<artifactId>jackson-core</artifactId>
				<version>2.1.0</version>
			</dependency>

			<dependency>
				<groupId>com.fasterxml.jackson.core</groupId>
				<artifactId>jackson-databind</artifactId>
				<version>2.1.0</version>
			</dependency>
			<dependency>
				<groupId>com.fasterxml.jackson.core</groupId>
				<artifactId>jackson-annotations</artifactId>
				<version>2.1.0</version>
			</dependency>
			<!-- <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId>
				<version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId>
				<artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> -->

			<dependency>
				<groupId>cglib</groupId>
				<artifactId>cglib-nodep</artifactId>
				<version>2.2.2</version>
			</dependency>

			<dependency>
				<groupId>javax.servlet.jsp.jstl</groupId>
				<artifactId>jstl-api</artifactId>
				<version>1.2</version>
			</dependency>

	</dependencies>

	<build>
		<finalName>mongos</finalName>
	</build>
</project>

spring mvc config

<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tool="http://www.springframework.org/schema/tool"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	                    http://www.springframework.org/schema/beans/spring-beans-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/aop
	                    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
	                    http://www.springframework.org/schema/tool
	                    http://www.springframework.org/schema/tool/spring-tool-4.0.xsd
	                 	http://www.springframework.org/schema/mvc
	                    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

	<!-- 启用spring mvc 注解 -->
	<!-- <context:annotation-config /> <mvc:annotation-driven /> <mvc:default-servlet-handler
		/> -->

	<!-- 静态资源访问 -->
	<mvc:resources mapping="/fornt/**" location="/fornt/" />
	<mvc:resources mapping="index.*" location="/" />
	<mvc:resources mapping="login.*" location="/" />

	<!--页面视图层信息 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView"></property>
		<property name="prefix" value="/"></property> <!--页面的前辍名 -->
		<property name="suffix" value=".html"></property>
		<!-- <property name="suffix" value=".jsp"></property> --> <!--页面的后辍名 -->
	</bean>

	<!-- 启动 Spring MVC 的注解功能,完成请求和注解 POJO 的映射 -->
	<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
		<property name="messageConverters"> <list> <bean class="org.springframework.http.converter.StringHttpMessageConverter"
		/> </list> </property> </bean> -->

	<!-- 获取bean -->
<!-- 	<bean id="sysApplicationContext" class="com.rui.pro.utils.sys.SysApplicationContext"> -->
<!-- 	</bean> -->
</beans>
<?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:p="http://www.springframework.org/schema/p"
	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"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tool="http://www.springframework.org/schema/tool"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	                    http://www.springframework.org/schema/beans/spring-beans-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/aop
	                    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
	                    http://www.springframework.org/schema/tool
	                    http://www.springframework.org/schema/tool/spring-tool-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/data/mongo
	                    http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">

	<!-- 注解扫描 com.rui.pro/** **.dao.***,**.service.***,**.controller.** -->
	<!-- com.rui.pro.dao.*.impl/**,com.rui.pro.service.*.impl/**,com.rui.pro.controller/** -->
	<context:component-scan base-package=" **.dao.***,**.service.***,**.controller.**"/>

	<bean
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
		<property name="order" value="0" />
	</bean>
	<bean id="messageAdapter"
		class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
		<property name="messageConverters">
			<list>
				<bean
					class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
			</list>
		</property>
	</bean>

	<bean
		class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
	<bean class="org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter" />

	<bean id="exceptionMessageAdapter"
		class="org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver">
		<property name="messageConverters">
			<list>
				<!-- Support JSON MappingJacksonHttpMessageConverter -->
				<bean
					class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
			</list>
		</property>
	</bean>

</beans>

spirng mongodb config

<?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:p="http://www.springframework.org/schema/p"
	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"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:tool="http://www.springframework.org/schema/tool"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	                    http://www.springframework.org/schema/beans/spring-beans-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/aop
	                    http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
	                    http://www.springframework.org/schema/tool
	                    http://www.springframework.org/schema/tool/spring-tool-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/data/mongo
	                    http://www.springframework.org/schema/data/mongo/spring-mongo-1.0.xsd">

	<context:property-placeholder
		location="classpath:sysconfig/properties/mongodb.properties" />

	<!-- <mongo:mongo id="mongo" replica-set="127.0.0.1:27017"> -->
	<!-- <mongo:options connections-per-host="100" -->
	<!-- threads-allowed-to-block-for-connection-multiplier="100" -->
	<!-- connect-timeout="60000" max-wait-time="30000" auto-connect-retry="true" -->
	<!-- socket-keep-alive="false" socket-timeout="60000" slave-ok="true" -->
	<!-- write-number="1" write-timeout="0" write-fsync="true" /> -->
	<!-- </mongo:mongo> -->

	<!-- <mongo:db-factory id="mongoDbFactory" dbname="rui" -->
	<!-- mongo-ref="mongo" /> -->

	<!-- <mongo:mapping-converter id="mongoConverter" -->
	<!-- base-package="org.rui.mongo.bean" /> -->
	<!-- <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> -->
	<!-- <constructor-arg name="mongoDbFactory" ref="mongoDbFactory" /> -->
	<!-- <constructor-arg name="mongoConverter" ref="mongoConverter" /> -->
	<!-- </bean> -->

	<mongo:mongo id="mongo" host="localhost" port="27017">
		<mongo:options connections-per-host="8"
			threads-allowed-to-block-for-connection-multiplier="4"
			connect-timeout="1000" max-wait-time="1500" auto-connect-retry="true"
			socket-keep-alive="true" socket-timeout="1500" slave-ok="true"
			write-number="1" write-timeout="0" write-fsync="true" />
	</mongo:mongo>

	<mongo:db-factory id="mongoDbFactory" dbname="rui"
		mongo-ref="mongo" />

	<mongo:mapping-converter base-package="org.rui.mongo.bean"
		id="mongoConverter" />

	<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
		<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
		<constructor-arg name="mongoConverter" ref="mongoConverter" />
	</bean>

	<mongo:repositories base-package="org.rui.mongo.bean" />

	<bean id="userDao" class="org.rui.mongo.dao.impl.UserDaoImpl">
		<property name="mongoTemplate" ref="mongoTemplate" />
	</bean>

	<!-- 使用annotation定义事务 -->
	<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->

	<!-- 扫描实现 -->
	<context:annotation-config />

</beans>

log4j.properties

##OFF\FATAL\ERROR\WARN\INFO\DEBUG\ALL
log4j.rootLogger=info,sysConsole,rollingFile
log4j.appender.sysConsole=org.apache.log4j.ConsoleAppender
log4j.appender.sysConsole.Target=System.out
log4j.appender.sysConsole.layout=org.apache.log4j.PatternLayout
#%l%n %20.30c
log4j.appender.sysConsole.layout.ConversionPattern=rui-%-8p%-10d{yyyy-MM-dd HH\:mm\:ss.S} %-10t %c{1} %3x%m%n

###########fileLog ronlling  ######################
log4j.appender.rollingFile=org.apache.log4j.RollingFileAppender
log4j.appender.rollingFile.Threshold=WARN
#${catalina.home} webappkey sys-core  webapp.root
log4j.appender.rollingFile.file=#${webapp.root}/log/sys.log
log4j.appender.rollingFile.Append=true
log4j.appender.rollingFile.MaxFileSize=20MB
log4j.appender.rollingFile.MaxBackupIndex=6
log4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout
log4j.appender.rollingFile.layout.ConversionPattern=rui-%-8p%-10d{yyyy-MM-dd HH\:mm\:ss.S} %-10t %c{1} %3x%m%n
#log4j.appender.ROLLING_FILE.layout.ConversionPattern=[framework] %d - %c -%-4r [%t] %-5p %c %x - %m%n

###### pack all set lvel # Print or not print the specified package
#log4j.logger.cn.com.systec.schedul=ERROR
#log4j.logger.cn.com.systec.utils=debug
#log4j.logger.org.hibernate.SQL=INFO

###########fileLog simple  ######################
#log4j.appender.fileLog=org.apache.log4j.DailyRollingFileAppender
#log4j.appender.fileLog.file=log4j/hd_service.log
#log4j.appender.fileLog.layout=org.apache.log4j.SimpleLayout

log4j.category.org.springframework.data.document.mongodb=DEBUG
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %40.40c:%4L - %m%n

热身动动

package org.rui.mongos;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.rui.mongo.bean.User;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoDbFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import com.mongodb.Mongo;
/**
 * main spring 简单mongodb 操作
 * http://docs.spring.io/spring-data/data-mongo/docs/1.6.2.RELEASE/reference/html/
 *
 */
public class Main {

	// log4j.category.org.springframework.data.document.mongodb=DEBUG
	// log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p
	// %40.40c:%4L - %m%n
	private static final Log log = LogFactory.getLog(Main.class);

	public static void main(String[] args) throws Exception {

		MongoOperations mongoOps = new MongoTemplate(new SimpleMongoDbFactory(new Mongo(), "rui"));
		//MongoOperations mongoOps = new MongoTemplate(new Mongo(), "rui");
		mongoOps.insert(new User(1, "Joe", 34));

		log.info(mongoOps.findOne(new Query(new Criteria("name").is("Joe")),
				User.class));

		//mongoOps.dropCollection("user");
	}

}

/**
 * output:
 * rui-INFO    2015-01-29 16:57:59.74 main       Main    User [id=54c9f6034c7147de6e158756, userId=1, name=Joe, age=34]
*/

dao 实现

package org.rui.mongo.dao.impl;

import java.util.List;

import org.rui.mongo.bean.User;
import org.rui.mongo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoOperations;
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.Repository;

@Repository
public class UserDaoImpl implements UserDao {

	private MongoOperations mongoTemplate;

	// @Autowired
	// @Qualifier("mongoTemplate")
	public void setMongoTemplate(MongoOperations mongoTemplate) {
		this.mongoTemplate = mongoTemplate;
	}

	public List<User> get() {
		List<User> user = mongoTemplate.findAll(User.class);
		return user;
	}

	public User getOne(Integer id) {
		User user = mongoTemplate.findOne(new Query(Criteria.where("userId")
				.is(id)), User.class);
		return user;
	}

	public void findAndModify(Integer id, Integer age) {
		mongoTemplate.updateFirst(new Query(Criteria.where("userId").is(id)),
				new Update().inc("age", age), User.class);
	}

	public void insert(User u) {
		mongoTemplate.insert(u);
	}

	public void removeOne(Integer id) {
		Criteria criteria = Criteria.where("userId").in(id);

		if (criteria != null) {
			Query query = new Query(criteria);
			if (query != null
					&& mongoTemplate.findOne(query, User.class) != null)
				mongoTemplate.remove(mongoTemplate.findOne(query, User.class));
		}

	}

	/**
	 * 修改多条 <br>
	 * ------------------------------<br>
	 *
	 * @param criteriaUser
	 * @param user
	 */
	public void update(User criteriaUser, User user) {
		Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());
		;
		Query query = new Query(criteria);
		Update update = Update.update("name", user.getName()).set("age",
				user.getAge());
		mongoTemplate.updateMulti(query, update, User.class);
	}

	/**
	 * 按条件查询, 分页 <br>
	 * ------------------------------<br>
	 *
	 * @param criteriaUser
	 * @param skip
	 * @param limit
	 * @return
	 */
	public List<User> find(User criteriaUser, int skip, int limit) {
		Query query = getQuery(criteriaUser);
		query.skip(skip);
		query.limit(limit);
		return mongoTemplate.find(query, User.class);
	}

	/**
	 * 根据条件查询出来后 再去修改 <br>
	 * ------------------------------<br>
	 *
	 * @param criteriaUser
	 *            查询条件
	 * @param updateUser
	 *            修改的值对象
	 * @return
	 */
	public User findAndModify(User criteriaUser, User updateUser) {
		Query query = getQuery(criteriaUser);
		Update update = Update.update("age", updateUser.getAge()).set("name",
				updateUser.getName());
		return mongoTemplate.findAndModify(query, update, User.class);
	}

	/**
	 * 查询出来后 删除 <br>
	 * ------------------------------<br>
	 *
	 * @param criteriaUser
	 * @return
	 */
	public User findAndRemove(User criteriaUser) {
		Query query = getQuery(criteriaUser);
		return mongoTemplate.findAndRemove(query, User.class);
	}

	/**
	 * count <br>
	 * ------------------------------<br>
	 *
	 * @param criteriaUser
	 * @return
	 */
	public long count(User criteriaUser) {
		Query query = getQuery(criteriaUser);
		return mongoTemplate.count(query, User.class);
	}

	/**
	 *
	 * <br>
	 * ------------------------------<br>
	 *
	 * @param criteriaUser
	 * @return
	 */
	private Query getQuery(User criteriaUser) {
		if (criteriaUser == null) {
			criteriaUser = new User();
		}
		Query query = new Query();
		if (criteriaUser.getId() != null) {
			Criteria criteria = Criteria.where("userId").is(criteriaUser.getId());
			query.addCriteria(criteria);
		}
		if (criteriaUser.getAge() > 0) {
			Criteria criteria = Criteria.where("age").gt(criteriaUser.getAge());
			query.addCriteria(criteria);
		}
		if (criteriaUser.getName() != null) {
			Criteria criteria = Criteria.where("name").regex(
					"^" + criteriaUser.getName());
			query.addCriteria(criteria);
		}
		return query;
	}

}

接口

package org.rui.mongo.dao;

import java.util.List;

import org.rui.mongo.bean.User;

public interface UserDao {

	List<User> get();

	User getOne(Integer id);

	/**
	 * 通过ID找到并修改
	 */
	public void findAndModify(Integer id, Integer age);

	void insert(User u);

	void removeOne(Integer id);

}

junit test

package org.rui.mongos;

import java.util.List;

import org.junit.BeforeClass;
import org.junit.Test;
import org.rui.mongo.bean.User;
import org.rui.mongo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

//"classpath:sysconfig/springmvc/spring-mvc.xml",

@org.junit.runner.RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:sysconfig/spring/db.xml" })
public class UserTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@Autowired
	UserDao userDao;

	/**
	 * 查询
	 * **/
	@Test
	public void getAll() {
		List<User> list = userDao.get();
		System.out.println("list:" + list);

		User user = userDao.getOne(1);
		System.out.println("user:" + user);
	}

	@Test
	public void findAndUpdate(){
		userDao.findAndModify(1, 10);
	}

	@Test
	public void insert(){
		User user=new User();
		user.setUserId(1);
		user.setName("hello");
		user.setAge(100);
		userDao.insert(user);
	}

	@Test
	public void removeOne(){
		userDao.removeOne(1);
	}

}

spring mvc 页面

package org.rui.mongo.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.rui.mongo.bean.User;
import org.rui.mongo.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("user")
public class UserController {

	@Autowired
	UserDao userDao;

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@RequestMapping("test")
	@ResponseBody
	public String test(){
		return "hello";
	}

	@ResponseBody
	@RequestMapping("get")
	public List<User> get(HttpServletRequest request,HttpServletResponse response){
		List<User> user=userDao.get();
		System.out.println(this.getClass().getName()+":"+user);
		return user;
	}

}

一个简单的结果 搞了半天

时间: 2024-10-29 19:12:11

spring mvc 集成mongoDB项目 例子的相关文章

Spring MVC集成slf4j-logback

1.  Spring MVC集成slf4j-log4j 关于slf4j和log4j的相关介绍和用法,网上有很多文章可供参考,但是关于logback的,尤其是Spring MVC集成logback的,就相对少一些了,而且其中一些也有着这样那样的问题.进入正题之前先简单介绍下Spring MVC集成slf4j-log4j的过程,如下: 1)      在pom.xml文件中添加slf4j-log4j的依赖,完成后的classpath中将新增三个jar包,分别是:slf4j-api.jar.log4j

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代码案例 5 1 Spring整合Mongodb 1.1 环境准备 1. mongodb官网 http://www.mongodb.org/,下载mongodb安装包和mongodb的java驱动包. mongodb安装包(下载地址http://www.mongodb.org/downloads).Mo

第二十六天 蛰伏的Hibernate遇到春日的暖阳 —Spring MVC 集成Hibernate使用(一)

6月7日,晴."纷纷红紫已成尘,布谷声中夏令新.夹路桑麻行不尽,始知身是太平人."        Hibernate和Spring的香艳相逢,不仅是Bean和Bean之间电光火石般的碰撞,也是XML和XML之间的萍水聚首.两种奇妙的架构,携手闯荡江湖,不仅塑造了依赖注入淋漓酣畅的快感,也让J2EE蹿红大半个地球. 第二十六天 蛰伏的Hibernate遇到春日的暖阳 -Spring MVC 集成Hibernate使用(一)

string与spring mvc集成多种技术构建复杂工程(转载)

使用spring集成其他技术,最基本的配置都是模板化的,比如配置视图模板引擎.数据库连接池.orm框架.缓存服务.邮件服务.rpc调用等,以spring的xml配置为例,我将这些配置过程整理出来,并不时更新,以备参考! spring 在普通的java工程中引入spring,只需要配置以下依赖 1 2 3 4 5 <dependency>     <groupId>org.springframework</groupId>     <artifactId>sp

Spring Boot集成mongodb数据库

一.认识mongodbMongoDB是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的.它支持的数据结构非常松散,是类似json的bson格式,因此可以存储比较复杂的数据类型.Mongo最大的特点是它支持的查询语言非常强大,其语法有点类似于面向对象的查询语言,几乎可以实现类似关系数据库单表查询的绝大部分功能,而且还支持对数据建立索引.二.Spring boot项目集成mongodb1.添加mongodb依赖 <dependency> <group

spring mvc 实战化项目之三板斧

接上文希望从一张表(tb_role_info 用户角色表)的CRUD展开spring mvc的项目实战化魅力. 开发技术选型:spring mvc+freemarker+bootstrap+mybatis+mysql. 项目目录结构: (1)业务表 tb_role_info -- ---------------------------- -- Table structure for `tb_role_info` 用户角色表 -- ---------------------------- DROP

IntelliJ idea创建Spring MVC的Maven项目

参考:http://my.oschina.net/gaussik/blog/385697?fromerr=Pie9IlFV 菜单File->New Project可进入上图界面,首先选择左边栏Maven,再配置JDK(一般如果之前添加了JDK的话会自动填充,如未添加的话点击旁边的New将 JDK目录导入即可).勾选“Create from archetype“,然后选中4处蓝色位置webapp,点Next,进入如下界面: 这里需要填写GroupId和ArtifactId还有Version,这三个

spring mvc学习之项目搭建

记录第一次搭建spring mvc项目 Eclipse创建动态web项目 项目路径下的WEB-INF/lib中导入以下包 在WEB-INF下新建文件 web.xml 内容: <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun

Spring MVC集成Spring Data Reids和Spring Session实现Session共享

说明:Spring MVC中集成Spring Data Redis和Spring Session时版本是一个坑点,比如最新版本的Spring Data Redis已经不包含Jedis了,需要自行引入.且最新版本的2.0.1会与Spring MVC 4.1.4有冲突,估计写法错了.所以要明确引入的Spring MVC版本和Spring Data Redis和Spring Session版本. 小提示:如果想要官方明确的版本可以参考Spring Boot的版本,比如我使用了1.4.7的Spring