`
zhanshi258
  • 浏览: 48265 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

mongodb与spring集成案例

 
阅读更多

假设现在我们已经安装好了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层。

 

 

 

分享到:
评论

相关推荐

    避开10大常见坑:DeepSeekAPI集成中的错误处理与调试指南.pdf

    在日常的工作和学习中,你是否常常为处理复杂的数据、生成高质量的文本或者进行精准的图像识别而烦恼?DeepSeek 或许就是你一直在寻找的解决方案!它以其高效、智能的特点,在各个行业都展现出了巨大的应用价值。然而,想要充分发挥 DeepSeek 的优势,掌握从入门到精通的知识和技能至关重要。本文将从实际应用的角度出发,为你详细介绍 DeepSeek 的基本原理、操作方法以及高级技巧。通过系统的学习,你将能够轻松地运用 DeepSeek 解决实际问题,提升工作效率和质量,让自己在职场和学术领域脱颖而出。现在,就让我们一起开启这场实用又高效的学习之旅吧!

    前端分析-2023071100789

    前端分析-2023071100789

    基于kinect的3D人体建模C++完整代码.cpp

    基于kinect的3D人体建模C++完整代码.cpp

    搞机工具箱10.1.0.7z

    搞机工具箱10.1.0.7z

    GRU+informer时间序列预测(Python完整源码和数据)

    GRU+informer时间序列预测(Python完整源码和数据),python代码,pytorch架构,适合各种时间序列直接预测。 适合小白,注释清楚,都能看懂。功能如下: 代码基于数据集划分为训练集测试集。 1.多变量输入,单变量输出/可改多输出 2.多时间步预测,单时间步预测 3.评价指标:R方 RMSE MAE MAPE,对比图 4.数据从excel/csv文件中读取,直接替换即可。 5.结果保存到文本中,可以后续处理。 代码带数据,注释清晰,直接一键运行即可,适合新手小白。

    性价比革命:DeepSeekAPI成本仅为GPT-4的3%的技术揭秘.pdf

    在日常的工作和学习中,你是否常常为处理复杂的数据、生成高质量的文本或者进行精准的图像识别而烦恼?DeepSeek 或许就是你一直在寻找的解决方案!它以其高效、智能的特点,在各个行业都展现出了巨大的应用价值。然而,想要充分发挥 DeepSeek 的优势,掌握从入门到精通的知识和技能至关重要。本文将从实际应用的角度出发,为你详细介绍 DeepSeek 的基本原理、操作方法以及高级技巧。通过系统的学习,你将能够轻松地运用 DeepSeek 解决实际问题,提升工作效率和质量,让自己在职场和学术领域脱颖而出。现在,就让我们一起开启这场实用又高效的学习之旅吧!

    基于ANSYS LSDyna的DEM-SPH-FEM耦合模拟滑坡入水动态行为研究,基于ANSYS LSDyna的DEM-SPH-FEM耦合的滑坡入水模拟分析研究,基于ansys lsdyna的滑坡入水

    基于ANSYS LSDyna的DEM-SPH-FEM耦合模拟滑坡入水动态行为研究,基于ANSYS LSDyna的DEM-SPH-FEM耦合的滑坡入水模拟分析研究,基于ansys lsdyna的滑坡入水模拟dem-sph-fem耦合 ,基于ANSYS LSDyna; 滑坡入水模拟; DEM-SPH-FEM 耦合,基于DEM-SPH-FEM耦合的ANSYS LSDyna滑坡入水模拟

    auto_gptq-0.6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

    auto_gptq-0.6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl

    复件 复件 建设工程可行性研究合同[示范文本].doc

    复件 复件 建设工程可行性研究合同[示范文本].doc

    13考试真题最近的t64.txt

    13考试真题最近的t64.txt

    Microsoft Visual C++ 2005 SP1 Redistributable PackageX86

    好用我已经解决报错问题

    嵌入式开发入门:用C语言点亮LED灯的全栈开发指南.pdf

    # 踏入C语言的奇妙编程世界 在编程的广阔宇宙中,C语言宛如一颗璀璨恒星,以其独特魅力与强大功能,始终占据着不可替代的地位。无论你是编程小白,还是有一定基础想进一步提升的开发者,C语言都值得深入探索。 C语言的高效性与可移植性令人瞩目。它能直接操控硬件,执行速度快,是系统软件、嵌入式开发的首选。同时,代码可在不同操作系统和硬件平台间轻松移植,极大节省开发成本。 学习C语言,能让你深入理解计算机底层原理,培养逻辑思维和问题解决能力。掌握C语言后,再学习其他编程语言也会事半功倍。 现在,让我们一起开启C语言学习之旅。这里有丰富教程、实用案例、详细代码解析,助你逐步掌握C语言核心知识和编程技巧。别再犹豫,加入我们,在C语言的海洋中尽情遨游,挖掘无限可能,为未来的编程之路打下坚实基础!

    auto_gptq-0.4.2-cp38-cp38-win_amd64.whl

    auto_gptq-0.4.2-cp38-cp38-win_amd64.whl

    自动立体库设计方案.pptx

    自动立体库设计方案.pptx

    手把手教你用C语言实现贪吃蛇游戏:从算法设计到图形渲染.pdf

    # 踏入C语言的奇妙编程世界 在编程的广阔宇宙中,C语言宛如一颗璀璨恒星,以其独特魅力与强大功能,始终占据着不可替代的地位。无论你是编程小白,还是有一定基础想进一步提升的开发者,C语言都值得深入探索。 C语言的高效性与可移植性令人瞩目。它能直接操控硬件,执行速度快,是系统软件、嵌入式开发的首选。同时,代码可在不同操作系统和硬件平台间轻松移植,极大节省开发成本。 学习C语言,能让你深入理解计算机底层原理,培养逻辑思维和问题解决能力。掌握C语言后,再学习其他编程语言也会事半功倍。 现在,让我们一起开启C语言学习之旅。这里有丰富教程、实用案例、详细代码解析,助你逐步掌握C语言核心知识和编程技巧。别再犹豫,加入我们,在C语言的海洋中尽情遨游,挖掘无限可能,为未来的编程之路打下坚实基础!

    性能对决:DeepSeek-V3与ChatGPTAPI在数学推理场景的基准测试.pdf

    在日常的工作和学习中,你是否常常为处理复杂的数据、生成高质量的文本或者进行精准的图像识别而烦恼?DeepSeek 或许就是你一直在寻找的解决方案!它以其高效、智能的特点,在各个行业都展现出了巨大的应用价值。然而,想要充分发挥 DeepSeek 的优势,掌握从入门到精通的知识和技能至关重要。本文将从实际应用的角度出发,为你详细介绍 DeepSeek 的基本原理、操作方法以及高级技巧。通过系统的学习,你将能够轻松地运用 DeepSeek 解决实际问题,提升工作效率和质量,让自己在职场和学术领域脱颖而出。现在,就让我们一起开启这场实用又高效的学习之旅吧!

    从零到一:手把手教你用Python调用DeepSeekAPI的完整指南.pdf

    在日常的工作和学习中,你是否常常为处理复杂的数据、生成高质量的文本或者进行精准的图像识别而烦恼?DeepSeek 或许就是你一直在寻找的解决方案!它以其高效、智能的特点,在各个行业都展现出了巨大的应用价值。然而,想要充分发挥 DeepSeek 的优势,掌握从入门到精通的知识和技能至关重要。本文将从实际应用的角度出发,为你详细介绍 DeepSeek 的基本原理、操作方法以及高级技巧。通过系统的学习,你将能够轻松地运用 DeepSeek 解决实际问题,提升工作效率和质量,让自己在职场和学术领域脱颖而出。现在,就让我们一起开启这场实用又高效的学习之旅吧!

    为什么你的switch总出bug?90%新手不知道的break语句隐藏规则.pdf

    # 踏入C语言的奇妙编程世界 在编程的广阔宇宙中,C语言宛如一颗璀璨恒星,以其独特魅力与强大功能,始终占据着不可替代的地位。无论你是编程小白,还是有一定基础想进一步提升的开发者,C语言都值得深入探索。 C语言的高效性与可移植性令人瞩目。它能直接操控硬件,执行速度快,是系统软件、嵌入式开发的首选。同时,代码可在不同操作系统和硬件平台间轻松移植,极大节省开发成本。 学习C语言,能让你深入理解计算机底层原理,培养逻辑思维和问题解决能力。掌握C语言后,再学习其他编程语言也会事半功倍。 现在,让我们一起开启C语言学习之旅。这里有丰富教程、实用案例、详细代码解析,助你逐步掌握C语言核心知识和编程技巧。别再犹豫,加入我们,在C语言的海洋中尽情遨游,挖掘无限可能,为未来的编程之路打下坚实基础!

    用deepseek变现实操流程

    用deepseek变现实操流程,小白必看。

    10个必知的DeepSeekAPI调用技巧:从鉴权到限流全解析.pdf

    在日常的工作和学习中,你是否常常为处理复杂的数据、生成高质量的文本或者进行精准的图像识别而烦恼?DeepSeek 或许就是你一直在寻找的解决方案!它以其高效、智能的特点,在各个行业都展现出了巨大的应用价值。然而,想要充分发挥 DeepSeek 的优势,掌握从入门到精通的知识和技能至关重要。本文将从实际应用的角度出发,为你详细介绍 DeepSeek 的基本原理、操作方法以及高级技巧。通过系统的学习,你将能够轻松地运用 DeepSeek 解决实际问题,提升工作效率和质量,让自己在职场和学术领域脱颖而出。现在,就让我们一起开启这场实用又高效的学习之旅吧!

Global site tag (gtag.js) - Google Analytics