springboot的版本1.5.17.RELEASE。
1、mongo的IP和端口
在resources下的application.properties中加入如下内容
spring.data.mongodb.host=localhost
spring.data.mongodb.database=test
spring.data.mongodb.port=27017
2、引入springboot mongo依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
3、使用mongoTemplate
经过步骤2和步骤1之后,可以直接注入mongoTemplate了,不需要我们再显示的定义bean了。
直接上代码了,如下所示,包含了保存、查询、分页查询、有条件的分页查询。
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import com.mjduan.springbootmongodb.domain.User;
/**
* @author dmj1161859184@126.com 2018-11-27 21:19
* @version 1.0
* @since 1.0
*/
@Slf4j
public class MongoTemplateTest extends SpringbootMongodbApplicationTests {
/**
* properties中设置了属性后,就会自动配置MontoTemplate
*/
@Autowired
private MongoTemplate mongoTemplate;
@Test
public void testFindAll() {
List<User> users = mongoTemplate.findAll(User.class);
System.out.println(users);
}
@Test
public void testAddUser(www.fengshen157.com/ ) {
User user = new User();
user.setAge(9);
user.setAddress("address");
user.setUsername("crupper");
user.setDate(new Date(www.mcyllpt.com));
mongoTemplate.save(user);
}
@Test
public void testPage() {
Pageable pageable = new PageRequest(1, 3);
Query query = new Query();
query.with(pageable);
List<User> users = mongoTemplate.find(query, User.class);
log.info(users.toString());
}
@Test
public void testPageSort() {
Pageable pageable = new PageRequest(1, 3);
Query query = new Query();
query.with(pageable);
query.with(new Sort(Sort.Direction.ASC, "age"));
List<User> users = mongoTemplate.find(query, User.class);
log.info(users.toString());
}
@Test
public void testPageSortMulti(www.michenggw.com) {
Pageable pageable = new PageRequest(0, 6);
Query query = new Query(www.lezongyule.com);
query.with(pageable);
query.with(new Sort(Sort.Direction.ASC, "age").and(new Sort(Sort.Direction.DESC, "date")));
List<User> users = mongoTemplate.find(query, User.class);
log.info(users.toString());
}
@Test
public void testCount() {
Query query = new Query();
query.with(new Sort(Sort.Direction.ASC, "age").and(new Sort(Sort.Direction.DESC, "date")));
long count = mongoTemplate.count(query, User.class);
log.info(count + "");
}
}
SpringbootMongodbApplicationTests如下所示:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.www.dasheng178.com boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootMongodbApplicationTests {
@Test
public void contextLoads() {
转载于:https://www.cnblogs.com/qwangxiao/p/10380921.html