Spring 中使用Jode-Money 与 mongoDB


//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); }

  

 

相关文章

MongoTemplate 是Spring Data MongoDB 中的一个核心类,为 S...
笔者今天要分享的是一个项目重构过程中如何将数据库选型由原...
mongodb/mongoTemplate.upsert批量插入更新数据的实现
进入官网下载官网安装点击next勾选同意,点击next点击custom...
头歌 MongoDB实验——数据库基本操作
期末考试复习总结