微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

  

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐