//gradle 引入joda-money implementation 'org.joda:joda-money:1.0.1' //引入mongoDB implementation 'org.springframework.boot:spring-boot-starter-data-mongodb'
编写 MoneyReadConverter.class
public class MoneyReadConverter implements Converter<Document, Money> { @Override public Money convert(Document source) { Document money = (Document) source.get("money"); double amount = Double.parseDouble(money.getString("amount")); String currency = ((Document) money.get("currency")).getString("code"); return Money.of(CurrencyUnit.of(currency), amount); } }
@SpringBootApplication @Slf4j public class MongoDemoApplication implements ApplicationRunner {
//更具类型注入bean @Autowired
//byName 注入mongoTemplate(多个bean,使用此方式) @Qualifier(value = "mongoTemplate") private MongoTemplate mongoTemplate; public static void main(String[] args) { SpringApplication.run(MongoDemoApplication.class, args); }
//注入一个自定义bean 相关信息可以查看spring -> autoconfig -> data -> -> mongo -> MongoDataAutoConfiguration.class @Bean public MongoCustomConversions mongoCustomConversions() { return new MongoCustomConversions(Arrays.asList(new MoneyReadConverter())); } @Override public void run(ApplicationArguments args) throws Exception {
//保存mongoDB Coffee espresso = Coffee.builder() .name("espresso") .price(Money.of(CurrencyUnit.of("CNY"), 20.0)) .createTime(new Date()) .updateTime(new Date()).build(); Coffee saved = mongoTemplate.save(espresso); log.info("Coffee {}", saved); List<Coffee> list = mongoTemplate.find( Query.query(Criteria.where("name").is("espresso")), Coffee.class); log.info("Find {} Coffee", list.size()); list.forEach(c -> log.info("Coffee {}", c)); //更新mongoDB UpdateResult result = mongoTemplate.updateFirst(query(where("name").is("espresso")), new Update().set("price", Money.ofMajor(CurrencyUnit.of("CNY"), 30)) .currentDate("updateTime"), Coffee.class); log.info("Update Result: {}", result.getModifiedCount()); Coffee updateOne = mongoTemplate.findById(saved.getId(), Coffee.class); log.info("Update Result: {}", updateOne); }