Java的最佳做法是将数据存储在数据库中吗? [英] Is it Java best practice to store dates as longs in your database?

查看:107
本文介绍了Java的最佳做法是将数据存储在数据库中吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的原因是,作为日期对象存储在任何数据库中的日期往往以特定格式写入,这可能与您在前端向用户呈现的内容有很大的不同。我也认为如果您的应用程序从不同类型的数据存储中提取信息,这将非常有用。一个很好的例子是MongoDB和SQL日期对象之间的区别。



但是,我不知道这是否是推荐的做法。我应该将日期保存为多长时间(以毫秒为单位)还是作为日期对象?

解决方案

我不能说与MongoDB的关系,但在SQL数据库中,不,这不是最佳实践。这并不意味着可能没有偶尔的用例,而是最佳实践,否则。



将它们存储为日期,将其作为日期检索。您最好的办法是设置数据库以将其存储为UTC(松散地,GMT),以便数据可移植,并且您可以根据需要使用不同的本地时间(例如,如果数据库由地理位置不同的用户使用) ,并在应用程序层(例如,通过 Calendar 或第三方日期库)处理从UTC到本地时间的任何转换。



将日期存储为数字意味着您的数据库难以报告,运行ad-hoc查询等。我犯了这个错误一次,这不是我会重复没有一个真的

My reason for doing so is that dates stored as date objects in whatever database tend to be written in a specific format, which may greatly differ from what you need to present to the user on the front-end. I also think it's especially helpful if your application is pulling info from different types of data stores. A good example would be the difference between a MongoDB and SQL date object.

However, I don't know whether this is recommended practice. Should I keep storing dates as longs (time in milliseconds) or as date objects?

解决方案

I can't speak for it in relation to MongoDB, but in SQL database, no, it's not best practice. That doesn't mean there might not be the occasional use case, but "best practice," no.

Store them as dates, retrieve them as dates. Your best bet is to set up your database to store them as UTC (loosely, "GMT") so that the data is portable and you can use different local times as appropriate (for instance, if the database is used by geographically diverse users), and handle any conversions from UTC to local time in the application layer (e.g., via Calendar or a third-party date library).

Storing dates as numbers means your database is hard to report against, run ad-hoc queries against, etc. I made that mistake once, it's not one I'll repeat without a really good reason. :-)

这篇关于Java的最佳做法是将数据存储在数据库中吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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