假设现在我们已经安装好了mongodb,并且都熟悉spring项目的配置。
spring 配置文件 spring-context.xml
与mongodb不相关的配置都已经去掉
<?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task" xmlns:mongo="http://www.springframework.org/schema/data/mongo" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <context:property-placeholder ignore-resource-not-found="false" location="classpath:mongodb.properties" /> <bean class="com.qing.utils.PropertyUtils"> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" /> <property name="ignoreResourceNotFound" value="false" /> <property name="locations"> <list> <value>classpath*:/mongodb.properties</value> </list> </property> </bean> <context:component-scan base-package="com.qing"/> <mongo:mongo id="mongo" replica-set="${mongo.host}"> <mongo: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> <mongo:db-factory id="mongoDbFactory" dbname="${mongo.database}" mongo-ref="mongo" username="${mongo.username}" password="${mongo.password}"/> <mongo:mapping-converter id="mongoConverter" base-package="com.qing.core.entity"> <mongo:custom-converters base-package="com.qing.core.entity" /> </mongo:mapping-converter> <bean id="nearest" class="com.mongodb.TaggableReadPreference.NearestReadPreference"/> <bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate"> <constructor-arg ref="mongoDbFactory" /> <constructor-arg ref="mongoConverter" /> <property name="writeConcern" value="SAFE" /> <property name="readPreference" ref="nearest" /> </bean> <mongo:repositories base-package="com.qing.core.repository" /> </beans>
mongodb.properties的属性配置文件
#The number of connections per host agreed, when the connection pool is used up, will be blocked, the default value is 10 --int mongo.connectionsPerHost=10 #multiplier for connectionsPerHost for # of threads that can block if connectionsPerHost is 10, and threadsAllowedToBlockForConnectionMultiplier is 5, then 50 threads can block more than that and an exception will be throw --int mongo.threadsAllowedToBlockForConnectionMultiplier=5 #Blocked thread connections from the connection pool gets the longest waiting time (MS) --int mongo.maxWaitTime=0 #To establish a socket connection when timeout (MS), the default value is 0 (infinite) mongo.connectTimeout=0 #Whether the control system in the event of a connection error retry,Defaults to false mongo.autoConnectRetry=false #This controls whether or not to have socket keep alive turned on (SO_KEEPALIVE). defaults to false --boolean mongo.socketKeepAlive=false #Socket timeout; this value will be passed to the Socket.setSoTimeout (int). The default value is 0 (infinite) --int mongo.socketTimeout=0 #Indicates whether the promised to drive from the secondary nodes or the slave node reads the data, defaults to false mongo.slaveOk=false mongo.database=mongodbtest mongo.host=192.168.23.4:27017 mongo.username=mongo mongo.password=123456
编写实体类、Controller、Service、Dao相关
实体类
import java.math.BigInteger; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Field; @Document(collection = "student") public class Student extends BaseDocument<BigInteger> implements Comparable<Student> { private static final long serialVersionUID = -3711325228602088792L; @Field("userId") private String userId; @Field("userName") private String userName; @Field("password") private String password; @Field("mobilPhone") private String mobilPhone; /////////get/set方法省略/////// @Override public int compareTo(Student o) { if (o == null) return -1; return this.userId.compareTo(o.getUserId()); } }
import java.io.Serializable; import org.springframework.data.annotation.Id; /** * <p> 抽象实体基类,提供统一的ID,和相关的基本功能方法 */ public abstract class BaseDocument<ID extends Serializable> extends AbstractDocument<ID> { @Id private ID id; @Override public ID getId() { return id; } @Override public void setId(ID id) { this.id = id; } }
import java.io.Serializable; /** * 抽象实体基类 */ public abstract class AbstractDocument<ID extends Serializable> implements Serializable { /** * Returns the identifier of the document. * * @return the id */ public abstract ID getId(); /** * Sets the id of the document. * * @param id the id to set */ public abstract void setId(final ID id); /* * (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (this.getId() == null || obj == null || !(this.getClass().equals(obj.getClass()))) { return false; } AbstractDocument<?> that = (AbstractDocument<?>) obj; return this.getId().equals(that.getId()); } /* * (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { return this.getId() == null ? 0 : this.getId().hashCode(); } }
dao
import java.math.BigInteger; import java.util.List; import org.springframework.data.mongodb.repository.Query; import org.springframework.data.repository.CrudRepository; import com.qing.core.entity.Student; public interface StudentRepository extends CrudRepository<Student, BigInteger>{ List<Student> findByUserIdAndUserName(String userId,String userName); @Query("{userId:?0,$or:[{userName:{ $regex:?1}},{password:{ $regex:?1}}]}") List<Student> findStudentByUserIdAndUserName(String userId, String userName); }
service
@Service public class StudentService { @Autowired private StudentRepository studentRepository; @Autowired MongoTemplate mongoTemplate; public Message create(Student stu) { this.studentRepository.save(stu); Message message = new Message(); message.setData(stu); return message; } public Message delete(Student stu) { // this.studentRepository.delete(stu); mongoTemplate.remove(new Query(Criteria.where("userName").is(stu.getUserName())), Student.class); Message message = new Message(); message.setData(stu); return message; } public void update(Student stu) { Update update = new Update(); update.set("password", stu.getPassword()); mongoTemplate.updateFirst(new Query(Criteria.where("userId").is(stu.getUserId())), update, Student.class); } public List<Student> findByUserIdAndUserName(Student stu) { String userId = stu.getUserId(); String userName = stu.getUserName(); List<Student> studentList = studentRepository.findByUserIdAndUserName(userId, userName); return studentList; } public List<Student> findStudents(Student stu) { String userId = stu.getUserId(); String userName = stu.getUserName(); List<Student> studentList = studentRepository.findStudentByUserIdAndUserName(userId, userName); return studentList; } }
controller
这个类就自己发挥写吧,就是springmvc的controller调用service层。
相关推荐
使用JAVA操作MongoDB进行简单测试,构建项目工具为Maven,使用的简单案例进行测试,包含增删改查的具体方式以及实现,pom.xml中集成了Spring所需jar包。欢迎下载。
spring 实践学习案例,与其它组件结合如 mybatis、jpa、dubbo、redis、mongodb、memcached、kafka、rabbitmq、activemq、shiro等 #### 软件架构 基于Java 1.8 #### Spring 版本 - 5.0.8.RELEASE #### 模块说明 - ...
spring boot 实践学习案例,与其它组件结合如 mybatis、jpa、dubbo、redis、mongodb、memcached、kafka、rabbitmq、activemq、elasticsearch、security、shiro等 #### Spring Boot 版本 - 2.0.3.RELEASE #### 模块...
- [spring-boot-redis](https://github.com/ityouknow/spring-boot-examples/tree/master/spring-boot-redis):Spring Boot 集成 Redis 示例 - [spring-boot-jpa]...
一个很完整,可以直接运行的案例,值得拥有。 springdata集成mongodb,实现了mongodb的基础操作功能
包含spring boot 监控、secruity与OAuth2鉴权、elasticSearch、Kafka、RabbitMQ、rocketMQ、MongoDB、Redis的集成使用案例,供大家在实际项目中做借鉴使用。
包含:集成MongoDB数据库,使用springframework中的MongoDB模板创建连接等 springboot-mysql 包含:集成mysql数据库、Druid连接池、mybatis generator等 springboot-oracle 包含:集成oracle数据库、Druid连接池、...
该项目利用了基于springboot + vue + mysql的开发...Java、Python、Node.js、Spring Boot、Django、Express、MySQL、PostgreSQL、MongoDB、React、Angular、Vue、Bootstrap、Material-UI、Redis、Docker、Kubernetes
dao与mybatis xml映射,与paginate插件集成//2015.04.08-通过查看源代码,此paginate插件使用原始jdbc连接,不建议在生产中使用 springmvc案例展示,带有json,请求参数,标头信息 2015.04.08-使用mongodb java ...
SpringBoot非官方教程 | 第十三篇:springboot集成spring cache 消息队列 SpringBoot非官方教程 | 第十四篇:在springboot中用redis实现消息队列 SpringBoot非官方教程 | 第十五篇:Springboot整合RabbitMQ 网络...
课程将会通过实际案例讲解,并且会提供完整的视频案例源码供学员学习使用,同时有需要的企业或学员可以直接拿本套教学案例代码来使用或者二次开发。 本课程设计的技术及工具如下: 后台服务架构:dubbo、spring-...
SpringBoot 全家桶 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程。 该框架使用了特定的方式...集成i18n实现后台国际化 springboot-jpa 整合Jpa实现增删改查 sp