在 pom.xml 中添加坐标
<!--mongdb-->
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>mongo-java-driver</artifactId>
<version>3.8.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-mongodb</artifactId>
<version>1.10.7.RELEASE</version>
</dependency>
在application.xml中添加以下代码
<!--mongdb-->
<mongo:mongo id="mongo" host="127.0.0.1" port="27017"></mongo:mongo>
<!-- mongoTemplate 对mongo一个封装 ,通过构造器注入-->
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongo"></constructor-arg>
<!-- wang 为数据库名 -->
<constructor-arg name="databaseName" value="wang"></constructor-arg>
</bean>
创建测试类
private MongoTemplate mongoTemplate =null; //私有化 MongoTemplate
@Before
public void before(){//通过 ClassPathXmlApplicationContext 读取配置文件
ClassPathXmlApplicationContext cpx=new ClassPathXmlApplicationContext("classpath:mongdb-spring.xml");
mongoTemplate =(MongoTemplate)cpx.getBean("mongoTemplate");
}
创建对应的实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Good {
@Id
private String goId; //为String 类型
private String goName;
private Integer goPrice;
}
如下增删改查 分页 操作
@Test
public void test1(){//保存数据
Good wang = new Good(null, "wang", 15);
mongoTemplate.save(wang);
}
@Test
public void test2(){//查询所有
List<Good> list=mongoTemplate.find(null,Good.class);
System.out.println(list);
}
@Test
public void test3(){//批量增加数据
for (int i = 0; i <10; i++) {
Good wang = new Good();
wang.setGoName("wang"+i);
wang.setGoPrice(15+i);
mongoTemplate.save(wang);
}
}
@Test
public void test4(){ //单条件查询
Query query = new Query();
Criteria where = new Criteria();
/*where.and("goPrice").is(17);*/ //等于17的数据
where.and("goPrice").lte(20); // 小于等于20
query.addCriteria(where);
List<Good> ts = mongoTemplate.find(query,Good.class);
System.out.println(ts);
}
@Test
public void test5(){//多条件查询
Query query = new Query();
Criteria where = new Criteria();
where.and("goPrice").gte(18);
Criteria where2 = new Criteria();
where2.and("goPrice").lte(20);
query.addCriteria(new Criteria().andOperator(where,where2)); //且 多条件查询 new Criteria().orOperator()//或者
List<Good> ts = mongoTemplate.find(query,Good.class);
System.out.println(ts);
}
@Test
public void Test6(){//分页
int page=1;
int rows=3;
Query query = new Query();
query.skip((page-1)*rows).limit(rows); //skip(开始下标).limit(每页条数)
List<Good> ts = mongoTemplate.find(query,Good.class);
System.out.println(ts);
}
@Test
public void Test7(){ //修改第一条数据
Query query = new Query();
Criteria criteria = new Criteria();
criteria.and("goPrice").is(15);
query.addCriteria(criteria);
Update update = new Update();
update.set("goPrice",12);
mongoTemplate.updateFirst(query,update,Good.class);
// mongoTemplate.updateMulti() 修改符合条件的所有数据
}
@Test
public void Test8(){//删除
Query query= new Query();
Criteria where= new Criteria();
where.and("goPrice").is(12);
query.addCriteria(where);
mongoTemplate.remove(query,Good.class);
}