Home > Software engineering >  What's the best way to store date in spring boot jpa?
What's the best way to store date in spring boot jpa?

Time:11-07

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

CodePudding user response:

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);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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

CodePudding user response:

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

  • Related