spring boot 初始化mongodb

方法一:springboot自动配置了支持mongodb。在启动springboot时会自动实例化一个mongo实例。可以在application.yml配置。

方法二:把配置连接信息存在数据库从数据库获取,项目启动时初始化。

用的到包:



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

Java代码: 

@Resource
private ConfigDao configDao;
@Bean
public MongoTemplate mongoTemplate() throws Exception {

//从数据库取连接信息

Config configs = configDao.getConfigs("MONGO");
String host = configs.getHost();
int port = configs.getPort();
String userName = configs.getUserName();
String password = configs.getPassword();
String databaseName = configs.getDatabaseName();

// 权限验证 MongoCredential
MongoCredential credential = MongoCredential.createScramSha1Credential(
userName, databaseName, password.toCharArray());
ServerAddress serverAddress = new ServerAddress(host, port);
MongoClient mongoClient = new MongoClient(serverAddress,
Arrays.asList(credential));
SimpleMongoDbFactory mongoDbFactory = new SimpleMongoDbFactory(
mongoClient, databaseName);
DbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDbFactory);
MappingMongoConverter converter = new MappingMongoConverter(
dbRefResolver, new MongoMappingContext());
// 不插入_class
converter.setTypeMapper(new DefaultMongoTypeMapper(null));
MongoTemplate mongoTemplate = new MongoTemplate(mongoDbFactory,
converter);
// 验证是否成功
// HqmgUser我定义的实体类
HqmgUser us = new HqmgUser();
us.setMgoid("o1000");
us.setConsumerid("10000001");
us.setName("行哥");
us.setPhone("1828888888");
us.setCreatetime(new Date().toString());
// 插入方法
mongoTemplate.insert(us, "t_user");
// 查询方法
QueryBuilder queryBuilder = new QueryBuilder();
queryBuilder.and("mgoid").is("o1000");
HqmgUser findOne = mongoTemplate.findOne(
new BasicQuery(queryBuilder.get()), HqmgUser.class, "t_user");
String name = findOne.getName();
System.out.println("name==============>"+name);
return mongoTemplate;
}

使用方法:注入mongoTemplate就可以直接调用方法了。如下:

@Resource
private MongoTemplate mongoTemplate;

//通过mgoid查询
public HqmgUser findHqmgUserById(查询条件,表名) {
QueryBuilder queryBuilder = new QueryBuilder();
queryBuilder.and("mgoid").is(查询条件);
return mongoTemplate.findOne(new BasicQuery(queryBuilder.get()), HqmgUser.class, 表名);
}

如果你是湖南的 欢迎加入 湖南人在深圳-Java群:557651502

你可能感兴趣的:(java)