时间:2021-07-01 10:21:17 帮助过:3人阅读
1 使用maven引入mongodb依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
2 配置mongodb,默认db为test
spring.data.mongo.host=127.0.0.1
spring.data.mongo.port=27017
spring.data.mongo.database=test
3 开发po实体类
public class Item {
@Id
private String id;
private String name;
private String price;
/**getters and setters*/
}
4 实现MongoRepository接口,该接口需要指定具体的泛型
public interface ItemRepository extends MongoRepository<Item, String> {
Item findByName(String name);
}
5 调用方式
public class ItemController {
@Autowired
private ItemRepository itemRepository;
@RequestMapping("/addItem")
@ResponseBody
public String addItem(String paramStr) {
JSONObject data = new JSONObject();
Item item = new Item();
item.setName("商品1");
item.setPrice("5.95");
try {
itemRepository.save(item);
} catch(Exception e) {
data.put("error", "Add item error");
}
return data.toString();
}
springboot配置mongodb
标签:tab data enc pen 需要 res cti cat ring