简体   繁体   中英

What's the best way to store date in spring boot jpa?

what's the best way of storing database date in spring boot entity?

For example, in my db I need to store smth like 2021-02-19 17:00 and then build queries on this date in my spring boot applicaiton

If you want to store date as string in your database you have many options, but answering to which one is better in my opinion it completely depends on your database and your mapping strategy, for example consider

 DateTimeFormatter firstFormatter = DateTimeFormatter.ofPattern("dd, MMM, yyyy", Locale.ENGLISH); LocalDate date = LocalDate.of(2021, Month.NOVEMBER, 7); String firstDateAsString = firstFormatter.format(date); System.out.println(firstDateAsString);

Which first firstFormatter.formate() accepts TemporalAccessor, as an other example

 DateFormat secondFormatter = new SimpleDateFormat("dd MM yyyy"); String secondDateAsString= secondFormatter.format(new Date()); System.out.println(secondDateAsString);

Note that the hibernate query payload and execution time will depends completely on your mapping and tokenizing the string accumulated by date.

Use LocalDateTime and the appropriate date column type in the database. Then you will be able to easily do date math (eg comparison) both in a database query and in Java if necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM