In this post I'll demonstrate different between Hibernate Date, Time and TimeStamp with Microsoft SQL Server database. For this demonstration I will use code base of "Spring Boot REST API with SQLServer 2019" post. Git code base for the initialization of the project can find in GIT CODE base.
Prerequisites
- You should have install java 1.8 or above.
- You should have Eclipse installed in your PC.
- Your PC should setup Maven installed and configured.
- MS SQL server need to be installed.
Modify Model class
For this demonstration I will add three parameters to out model class "Book". Those three parameters will map to respective columns in "BOOKS" table which store TIMESTAMP, DATE and TIME.
@Temporal(TemporalType.TIMESTAMP) private Date timeStamp; @Temporal(TemporalType.DATE) private Date date; @Temporal(TemporalType.TIME) private Date time;
I have added above three parameters and relevant geter/setter methods.We can define the preferred mapping with the @Temporal annotation. As you can see in above code, it takes a TemporalType enum as a value. The enum allows you to select the SQL type (DATE, TIME or TIMESTAMP) which you want to use.
Modify Service class
Then lets update the service method of setDateTime which set values for book objects time, date and time stamp.
private void setDateTime(Book book){ Date date= Calendar.getInstance().getTime(); book.setTimeStamp(date); book.setDate(date); book.setTime(date); }
Then call this setDateTime method from saving method of Book saveBookInJSON method.
Run the application
In order to run first we have to perform maven install command and then we can run the application
Go to run debug configuration and add following command
spring-boot:run
Then run the application by click on Run button
After successful execution you should be able to see similar output as show below.
Lets Test the application
Then lets add new Book in to API
curl -H "Accept: application/json" -H "Content-type: application/json" -X POST -d "{ \"isbmNumber\":\"9999\", \"name\":\"How to develop API\", \"description\":\"sample book\", \"auther\":\"Nirmal Balasooriya \" }" http://localhost:8080/saveOrUpdate
For this one following output will return
{"code":"1","desc":"Book save successful","t":"9999"}
If you check the database then you could see the saved data in the database as show in below.
Saved details in the Database. |
As you can see in the database Date, Time and TimeStamp values can be see as show below.
date : 2020-04-12
timestamp : 2020-04-12 17:45:28.6590000
You can be find updated code base in following GIT HUB location.
No comments:
Post a Comment