spring boot整合mongodb
- **更新pom.xml,在pom.xml中加入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency
** 配置连接信息
在application.yml中加入如下信息:–不含用户名和密码(mongo默认)
Spring:
data:
mongodb:
uri: mongodb://localhost:27017/mongo_bi
–包含用户名和密码
Spring:
data:
mongodb:
uri:// mongodb:username:password@localhost:27017/mongo_bi
- ** 编写对应的实体类
@Document(collection = "customer")
public class CustomerMongo {
@Id
private ObjectId id;
private String name;
private Integer age;
@Override
public String toString() {
return "CustomerMongo{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
这里的id类型需要注意一下:是org.bson.types.ObjectId类型的!
- **再来写一个mongoRespository
public interface CustomerRepository extends MongoRepository<CustomerMongo,Long>{
/**
* 通过name查找信息
* @param name
* @return
*/
List<CustomerMongo> findAllByName(String name);
List<CustomerMongo> findAllByNameAndAge(String name,Integer age);
}
这里的许多方法都是写好了的,用 就可以了!
测试
@SpringBootTest
@RunWith(SpringRunner.class)
public class MongoTest {
private static final Logger logger = LoggerFactory.getLogger(MongoTest.class);
@Autowired
CustomerRepository customerRepository;
@Autowired
MongoTemplate mongoTemplate;
@Test
public void getData() {
List<CustomerMongo> customerMongo = customerRepository.findAllByNameAndAge("wangwei",18);
logger.info(customerMongo.toString());
/*Query query = new Query(Criteria.where("name").is("wangwei"));
CustomerMongo customerMongo = mongoTemplate.findOne(query, CustomerMongo.class);
logger.info(customerMongo.toString());*/
}
}
注释掉的代码是用mongoTemplate写的,效果是一样的。