spring在couchbase

时间:2016-06-20 10:46:00

标签: java spring-boot spring-data couchbase

我使用Spring在Couchbase中保存文档。对于某些字段,会添加额外信息。

POJO:

 @Document public class PlayerTxn implements Serializable {

    private static final long serialVersionUID = -2569497126561L;

    @Id     private String id;

    @Field  private Date txnDate;

    @Field  private BigDecimal wagerAmount;

    @Field  private BigDecimal pointsAwarded;

    @Field  private String segment;

RequiredResult:

{   "txnDate": 234234234324,   "wagerAmount": 234.33,   "pointsAwarded":
 23.2,   "segment": "xxx" }

最终结果:

{   "_class": "com.app.model.PlayerTxn",   "segment":
 "xxx",   "wagerAmount": {
     "intCompact": 24312,
     "scale": 2,
     "precision": 5,
     "stringCache": "243.12"   },   "pointsAwarded": {
     "intCompact": -9223372036854776000,
     "scale": 38,
     "precision": 0,
     "intVal": {
       "signum": 1,
       "bitCount": 0,
       "mag": [
         3800,
         -457875904,
         -1778440383,
         -1805069212,
         295579091
       ],
       "lowestSetBit": 0,
       "firstNonzeroIntNum": 0,
       "bitLength": 0
     }   },   "txnDate": 1466417747057 }

必须为BigDecimal编写customConverter。

但仍然是" _class"正在添加到文档中。不知道如何删除它?

1 个答案:

答案 0 :(得分:1)

看起来您需要为BigDecimal值添加​​自定义转换器,例如:

// extend or add a customized couchbase config like this
public class CustomCouchbaseConfig extends AbstractCouchbaseConfiguration {

    @Override
    public CustomConversions customConversions() {
        return new CustomConversions(Arrays.asList(
            BigDecimalToString.INSTANCE,     
            StringToBigDecimalConverter.INSTANCE));
    }

    @WritingConverter
    public static enum BigDecimalToString implements Converter<BigDecimal, String> {
        INSTANCE;

        @Override
        public String convert(BigDecimal source) {
            // or a more appropriate implementation
            return source.toString() ;
        }

    }


    @ReadingConverter
    public static enum StringToBigDecimalConverter implements Converter<String, BigDecimal> {
        INSTANCE;

        @Override
        public BigDecimal convert(String source) {
            return new BigDecimal(source);
        }

    }

}

确保使这些转换器方法无效!

有关更多信息,请参阅Spring Data Couchbase参考: http://docs.spring.io/spring-data/couchbase/docs/2.1.2.RELEASE/reference/html/#datatypes

编辑: 关于_class属性,请参阅this SO question以及Oliver Giercke关于_class背后的原因的答案。 问题针对的是MongoDB,但也很容易为Couchbase翻译。