【MongoDB】springboot项目里BigDecimal和Decimal128类型的转换

本文介绍如何在MongoDB中使用Decimal128类型来存储高精度数字,并提供了Java环境下BigDecimal与MongoDB Decimal128之间的转换实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码:https://github.com/nieandsun/mongstudy

  • 我觉得我现在应该是我们组里mongo用的最菜的,因此打算系统的学习一下mongo!!!

1.简介

java里会用BigDecimal类型来表示精度要求较高的数字,而mongo从3.4开始也有了一个表示高精度数字的类型即Decimal128;但是两者之间不能直接进行转换.

描述一下现象,大家可以自己亲手试一下:

  • 如果java对象里有BigDecimal类型的变量,直接存到mongo,在mongo里的类型将变为String类型
  • java可以将mongo里为String类型的数字读成BigDecimal类型.

这样一看,BigDecimal和Decimal128的转换貌似成了鸡肋.其实并非如此,举个最简单的栗子,在做查询时,如果查某两个数之间满足条件的数据,字符串的比较和数字的比较就会变得不同.

2.Demo

  • 实体类
package com.nrsc.mongostudy.domain;
import lombok.Data;
import org.springframework.data.annotation.Id;
import java.math.BigDecimal;
@Data
public class Book {
    @Id
    private String id;
    /**书名*/
    private String name;
    /** 价格*/
    private BigDecimal price;
    /**简介*/
    private String info;
    /**出版社*/
    private String publish;

    @Override
    public String toString() {
        return "Book{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", info='" + info + '\'' +
                ", publish='" + publish + '\'' +
                '}';
    }
}
  • BigDecimalToDecimal128Converter
package com.nrsc.mongostudy.convert;
import org.bson.types.Decimal128;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.WritingConverter;
import java.math.BigDecimal;

/**
 * java-->mongo  即BigDecimal变为Decimal128的转换器
 */
@WritingConverter//告诉spring往数据库写的时候用这个转换
public class BigDecimalToDecimal128Converter implements Converter<BigDecimal, Decimal128> {
    @Override
    public Decimal128 convert(BigDecimal bigDecimal) {
        return new Decimal128(bigDecimal);
    }
}

  • Decimal128ToBigDecimalConverter
package com.nrsc.mongostudy.convert;
import org.bson.types.Decimal128;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.convert.ReadingConverter;
import java.math.BigDecimal;

/**
 * mongo--->java  即Decimal128变为BigDecimal的转换器
 */
@ReadingConverter //告诉spring从数据库读的时候用这个转换
public class Decimal128ToBigDecimalConverter implements Converter<Decimal128, BigDecimal> {
    @Override
    public BigDecimal convert(Decimal128 decimal128) {
        return decimal128.bigDecimalValue();
    }
}
  • MongoCustomConversions
package com.nrsc.mongostudy.config;
import com.nrsc.mongostudy.convert.BigDecimalToDecimal128Converter;
import com.nrsc.mongostudy.convert.Decimal128ToBigDecimalConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class MongoConvertConfig {
    /**
     * mongoCustomConversions会由spring进行管理,
     * 按照加入的转换器,在数据库读写时对数据类型进行转换
     *
     * @return
     */
    @Bean
    public MongoCustomConversions mongoCustomConversions() {
        List<Converter<?, ?>> converterList = new ArrayList<>();
        converterList.add(new BigDecimalToDecimal128Converter());
        converterList.add(new Decimal128ToBigDecimalConverter());
        return new MongoCustomConversions(converterList);
    }
}
  • 测试类
package com.nrsc.mongostudy;

import com.nrsc.mongostudy.domain.Book;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.math.BigDecimal;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MongostudyApplicationTests {

    @Autowired
    private MongoTemplate mongoTemplate;
    @Test
    public void testSave() {
        Book book = new Book();
        //id不写mongo会自动生成_id,如果写了会用我们自己写的
        //book.setId("3");
        book.setName("新华字典");
        book.setInfo("好书啊");
        //注意如果用new BigDecimal(22.9900001)无法完成转换---异常有兴趣的可以自己看一下
        book.setPrice(BigDecimal.valueOf(22.9900001)); 
        book.setPublish("新华出版社");
        mongoTemplate.save(book);
    }

    @Test
    public void testQueryAll() {
        List<Book> all = mongoTemplate.findAll(Book.class);
        System.err.println(all);
    }
}

3.结果展示

  • 运行完testSave可以在数据库里看到如下结果

在这里插入图片描述

  • 运行完testQueryAll可以在控制台看到如下结果:

在这里插入图片描述

### MongoDBBigDecimal 类型的存储与操作 #### 存储方式 在 MongoDB 中,`BigDecimal` 并不是一个原生支持的数据类型。通常情况下,Java 的 `BigDecimal` 对象会被序列化为字符串或者双精度浮点数(Double)。然而,这种转换可能会带来一些问题,比如精度丢失或无法精确表示某些数值。为了确保高精度计算的需求被满足,推荐将 `BigDecimal` 转换为 BSON Decimal128 类型进行存储[^5]。 BSON Decimal128 是一种固定长度的 128 位十进制浮点数格式,能够提供更高的精度范围,非常适合金融领域或其他需要高度准确性的地方。当使用 Java 驱动程序时,可以通过自定义编码解码逻辑来实现 `BigDecimal` BSON Decimal128 之间的映射。 #### 插入数据示例 以下是插入包含 `BigDecimal` 数据的例子: ```java import org.bson.codecs.configuration.CodecRegistries; import org.bson.codecs.pojo.PojoCodecProvider; import com.mongodb.MongoClientSettings; import com.mongodb.client.MongoClients; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.types.Decimal128; public class BigDecimalExample { public static void main(String[] args) { // 创建 MongoClient 连接设置 var codecRegistry = CodecRegistries.fromProviders(PojoCodecProvider.builder().automatic(true).build()); var settings = MongoClientSettings.builder() .codecRegistry(codecRegistry) .build(); try (var mongoClient = MongoClients.create(settings)) { MongoDatabase database = mongoClient.getDatabase("test"); MongoCollection<Document> collection = database.getCollection("bigDecimalCollection"); // 定义一个 BigDecimal 值并将其Decimal128 java.math.BigDecimal bigDecimalValue = new java.math.BigDecimal("123456789.123456789"); Document document = new Document("value", new Decimal128(bigDecimalValue)); // 插入文档 collection.insertOne(document); System.out.println("Data inserted successfully."); } } } ``` 上述代码展示了如何创建一个带有 `BigDecimal` 字段的文档,并将其作为 Decimal128 类型写入数据库中[^6]。 #### 查询数据示例 查询具有 `BigDecimal` 类型字段的内容可以按照如下方式进行: ```java // 构造查询条件 java.math.BigDecimal queryValue = new java.math.BigDecimal("123456789.123456789"); FindIterable<Document> results = collection.find(eq("value", new Decimal128(queryValue))); // 输出结果 results.forEach(doc -> System.out.println(doc.toJson())); ``` 此部分说明了基于特定值查找记录的方法,其中同样涉及到了 Decimal128 的运用[^7]。 #### 性能考量 如果集合规模非常庞大,则应考虑建立适当索引来优化性能。例如,在经常按某个大数值列筛选的情况下,可针对该列构建索引以减少全表扫描带来的负担[^1]。 ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nrsc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值