在Firebase数据库中保存LocalDate(Java.time)的对象 [英] Save object of LocalDate (Java.time) in Firebase database

查看:86
本文介绍了在Firebase数据库中保存LocalDate(Java.time)的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类(例如Class A),它有一个字段LocalDate localDate(Java.time),我考虑过使用LocalDate,因为我想保存'date'而没有'time'.我想将此类A的对象保存到Firebase数据库.因为LocalDateserializable,所以我认为我可以轻松地将其保存在FB数据库中,但是在实际实现它时,出现了以下错误:

I have a class (say Class A) which has a field LocalDate localDate (Java.time), I have considered using LocalDate as I want to save the 'date' without 'time'. I want to save an object of this class A to firebase database. As LocalDate is serializable I thought I will easily be able to save it on the FB Database but while actually implementing it, I got this error:

'firebase.database.DatabaseException: Found conflicting getters for name: getChronology'

我在Twitter上发布了此内容,并得到了@puf和doug的快速回复.

I posted this on twitter and got a quick response from @puf and doug.

我确实得到了一些帮助,但我仍在寻找一些问题的答案:

I did get some help but I'm still looking for answer to a couple of questions:

  1. 是否有一种简单且通用的方法将模型中的字段保留为LocalDate,而在存储到数据库中时仅将其用作String?类似于overridingtoString()方法(尽管覆盖toString()在这里不起作用,因为Firebase不使用可序列化来获取对象数据).

  1. Is there an easy and a generic way somehow to keep the field in my model as LocalDate and yet just use it as String while storing in database? Something like overriding the toString() method (though overriding toString() wont work here as Firebase does not use serializable to get object data).

如何在没有时间的情况下将日期保存到Firebase数据库"的最佳解决方案是什么?

What would be the best solution to "How to save date without time to Firebase Database"?

推荐答案

正如我在后续推文中所暗示的那样,符合您的最大利益:

As I implied in my followup tweet, it's in your best interest to:

  1. 使用普通的long值表示时间点
  2. 将LocalDate(或任何派生对象)的使用推迟到实际需要其日期处理功能的应用程序的其他部分.

原因如下:

  1. 存储时间长意味着您可以通过该单个值对数据库查询进行排序和过滤.
  2. 您无需弄乱POJO即可提供获取器和设置器,这些获取器和设置器尝试将long日期转换为该派生对象,甚至不知道是否要使用它.根据需要延迟更简单,更有效.
  1. Storing times as a long means you have the ability to sort and filter your database queries by that single value.
  2. You don't have to mangle your POJO to provide getters and setters that try to convert a long date to that derived object, without even know if it's going to be used. It's simpler and more efficient to delay as needed.

最重要的是,不将实用程序类与数据模型一起使用更容易,更灵活,更高效.数据模型包含已存储的原始数据时,它们可以与Firebase更好地配合使用.

The bottom line is that it's easier, more flexible, and more efficient NOT to use a utility class with data models. Data models work better with Firebase when they contain the raw data stored.

请注意,在Firestore中,大多数平台上对本机Date对象类型都有特殊处理.因此,如果您想移植到Firestore,最好使用平台的日期类型来读写Firestore时间戳字段.

Note that with Firestore, there is special handling for native Date object types on most platforms. So if you ever want to port to Firestore, it's actually better to use your platform's date type to read and write Firestore timestamp fields.

这篇关于在Firebase数据库中保存LocalDate(Java.time)的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆