spring boot 集成mongodb

阅读更多

1.pom.xml添加依赖包


  org.springframework.boot
  spring-boot-starter-data-mongodb

 

2.application.yml文件添加加配置

spring:
  data:
    mongodb:
      uri: mongodb://localhost/test

 若有副本集,则可以

mongodb://user:[email protected]:12345,mongo2.example.com:23456/test

 

3.通过mongoTemplate操作mongodb

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { Application.class })
@ActiveProfiles(value = "dev")
public class MyTest {

	@Resource
	private MongoTemplate mongoTemplate;

	@Test
	public void test1() {
		try {
			LogInfo info = new LogInfo();
                        //set data...
			mongoTemplate.save(info, "log");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testFindAll() {
		List list = mongoTemplate.findAll(LogInfo.class, "log");
		for (LogInfo info : list) {// 查出所有结果,包括不是LogInfo对象的数据
			System.out.println(info.getTableName());
			System.out.println(info.getColumnInfoList().size());
		}
	}

	@Test
	public void testFindBy() {
		Query query = Query.query(Criteria.where("name").is("user").and("recordId").is("1001"));
		List list = mongoTemplate.find(query, LogInfo.class, "log");
		for (LogInfo info : list) {
			System.out.println(info.getTableName());
			for (ColumnInfo col : info.getColumnInfoList()) {
				System.out.println(col.getName() + ":" + col.getValue());
			}
		}
	}

	@Test
	public void testFindPage() {// 小数据量分页,可跳页
		Query query = Query.query(Criteria.where("name").is("user"));
		Pageable pageable = new PageRequest(2, 3);
		query.with(pageable).with(new Sort(Direction.DESC, "_id"));
		Long count = mongoTemplate.count(query, "log");
		System.out.println("count:" + count);
		List list = mongoTemplate.find(query, LogInfo.class, "log");
		for (LogInfo info : list) {
			System.out.println(info.getTableName());
			for (ColumnInfo col : info.getColumnInfoList()) {
				System.out.println(col.getName() + ":" + col.getValue());
			}
		}
	}

	@Test
	public void testFindBigPage() {// 大数据量分页,不可跳页
		String lastId = "xxx";
		BasicDBObject query = new BasicDBObject();
		query.put("name", "user");
                int count = mongoTemplate.getCollection("log").find(query).size();
		query.put("_id", new BasicDBObject("$lt", new ObjectId(lastId)));
		DBCursor cursor = mongoTemplate.getCollection("log").find(query).sort(new BasicDBObject("_id", -1))
				.limit(3);
		while (cursor.hasNext()) {// 大数据量对象转换,也推荐用这方式
			DBObject obj = cursor.next();
			ObjectId id = (ObjectId) obj.get("_id");
			System.out.println(id.toString());
			BasicDBList cols = (BasicDBList) obj.get("columnInfoList");
			for (Object col : cols) {
				DBObject o = (DBObject) col;
				System.out.println(o.get("name") + ":" + o.get("value"));
			}
		}
	}

}

 

@Document
public class LogInfo {
	private String id;
	private String name;
	private String recordId;
	private List columnInfoList;
}

@Document
public class ColumnInfo {
	private String name;
	private String value;
}

 

 

你可能感兴趣的:(mongodb)