此内容,适合对mongodb和spring有相关基础者参考!
1.启动mongodb后,在mongo中创建相关database collection 和 域 与下列实体类对应
public class Student implements Serializable{
private static final long serialVersionUID = 1L;
private String name;
private int age;
private String address;
private String sex;
2. 查看对应的库
C:\Users\ThinkPad>mongo
MongoDB shell version v3.4.1
connecting to: mongodb://127
MongoDB server version: 3.4.
Server has startup warnings:
2018-12-13T09:07:12.288+0800
2018-12-13T09:07:12.288+0800
ol is not enabled for the da
2018-12-13T09:07:12.288+0800
te access to data and config
2018-12-13T09:07:12.288+0800
2018-12-13T09:07:12.288+0800
r update is not installed, w
2018-12-13T09:07:12.288+0800
> show dbs
itcastdb 0.001GB
库名为 : itcastdb collection 为: student
3. 建立maven工程:导入相关依赖
<!-- 数据库驱动 -->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongodb-driver</artifactId>
<version>3.4.3</version>
</dependency>
<!-- springdata整合mongodb -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.10.6.RELEASE</version>
</dependency>
4.由于本库测试没有账号和密码: mongodb.properties
mongo.host=127.0.0.1
mongo.port=27017
5. 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:mongo="http://www.springframework.org/schema/data/mongo"
xmlns:repository="http://www.springframework.org/schema/data/repository"
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-4.3.xsd
http://www.springframework.org/schema/data/mongo
http://www.springframework.org/schema/data/mongo/spring-mongo-1.8.xsd
http://www.springframework.org/schema/data/repository
http://www.springframework.org/schema/data/repository/spring-repository-1.5.xsd">
<context:property-placeholder location="classpath:properties/mongodb.properties" />
<context:component-scan base-package="com.mongo" />
<mongo:mongo-client id="mongo" host="${mongo.host}" port="${mongo.port}">
</mongo:mongo-client>
<mongo:db-factory id="mongoDbFactory" dbname="aaaa"
mongo-ref="mongo" />
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg name="mongoDbFactory" ref="mongoDbFactory" />
</bean>
</beans>
6.Dao方法,只测试与mongodb的连接部分
public void save(Student entity) {
mongoTemplate.save(entity);
}
7.测试类
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:spring/mongodb.xml")
public class mongoTest {
@Autowired
private IMongoDao MongoDaoImpl;
@Test
public void test1(){
Student ub=new Student();
ub.setName("哈哈哈哈");
MongoDaoImpl.save(ub);
System.out.println("插入成功!");
}
|
|