in my MySql database I store date as DATE type so I store only YYYY-MM-DD without any information about time (in the other table I use DATETIME to store also time information).
My entity is :
#Entity
#Table(name = "clientlicense", catalog = "ats")
public class ClientLicense implements java.io.Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer idClientLicense;
private Date startDate;
private Date endDate;
private int counter;
private String macAddress;
private String cpuId;
But when i get startDate and endDate from my WebUi I receive even the time like 2016-01-29 00:00:00.0
How can I store only the date as into database? Do I have to work in my HTML code?Thanks
Try with #Temporal JPA annotations.
Anotating your field and changing the type should help:
#Temporal(TemporalType.TIMESTAMP)
private java.util.Date startDate;
The valid values are:
TemporalType.DATE
TemporalType.TIME
TemporalType.TIMESTAMP
It is equivalent of
DATE – equivalent of java.sql.Date
TIME – equivalent of java.sql.Time
TIMESTAMP – equivalent of java.sql.Timestamp
Your entity mapping seems ok to me. The java.util.Date class ships also time information.
You will need to format the date object on the web tier. The implementation depends on the technology you are using on the front-end.
For example if you are on a plain JSP page you could format with a java.text.SimpleDateFormat object.
Related
I am trying to solve a problem which seems to be tricky on which I got stuck. Could you help please?
In Spring Boot I have an object Holiday for national holidays persisted on a MySQL database. The object Holiday contains the following attributes:
(...)
#Column(name = "title")
private String HolidayTitle;
#Column(name = "date")
private String holidayDate;
#Column(name = "updated")
private LocalDateTime updated;
#Column(name = "country")
private String country;
(...)
But I am interested on the updated attribute, which is stored, for example, as 2021-10-26 20:54:48 in the database. I want to format it as dd-MM-yyyy HH:mm to Thymeleaf, but it consists of a list of Holiday objects with different attributes.
In controller, the list is being retrieved as the following:
#GetMapping("/getAllHolidays")
public String getAllHolidays(Model theModel) {
List<Holiday> theHolidays = holidayService.findAll();
theModel.addAttribute("holidays", theHolidays);
return "holidays";
}
How to format only the attribute updated for all holiday objects in the list theHolidays by using DateTimeFormatter?
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
Is it possible to achieve this by using Java stream?
You can parse the dates using Java Stream like this:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
List<String> formattedDates = theHolidays.stream()
.map(Holiday::getUpdated)
.map(formatter::format)
.collect(Collectors.toList());
But if you're using thymeleaf, you can format your dates like this:
<tr th:each="holiday : ${holidays}">
<td th:text="${#temporals.format(holiday.updated, 'dd-MM-yyyy HH:mm')}"></td>
</tr>
I have a property with type Date and input for this field would be like 2020-11-08T10:00:00+05:30.
When I get this object in Json response it is not giving in same format. I am trying to accomplish this using #JsonFormat but I saw there is some issue with this approach from below link
https://github.com/FasterXML/jackson-databind/issues/1266
This is how I have date field.
#JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ssZ")
private Date startDate;
Is there any solution to accomplish or I should go with Calendar type and add custom deserialization like below.
#JsonDeserialize(using = DateDeserializer.class)
private Calendar startDate;
I am trying to find a Java Time Type that can be persisted to a column of type TIMESTAMP WITH TIME ZONE in the Oracle DB. The Java type needs to have the Time Zone as part of it. Because of the way the application was written, the Java Calendar type was used (also, the Java Calendar type has Time Zone that is part of it)
TRIAL ONE:
I did try to use the Calendar directly (with no serializer) with this code:
dateStr was in a pattern of: "MM-dd-yyyy hh:mm:ss a"
ZoneLoc was for the timezone: ex: America/Chicago, US/Eastern, etc.
public Calendar convDateStrWithZoneTOCalendar(String dateStr,
String ZoneLoc) throws Exception {
String string = dateStr;
String pattern = this.getPattern();
Date date = new SimpleDateFormat(pattern).parse(string);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
TimeZone tz = TimeZone.getTimeZone(ZoneLoc);
calendar.setTimeZone( tz );
return calendar;
}
when using this, the correct Zone Location was not set. For example, I would try to set ZoneLoc to US/Hawaii and when data was saved to the DB, it would be something like
23-SEP-19 10.03.11.000000 AM -05:00 And (-05:00) does not represent US/Hawaii
TRIAL TWO
It is for this reason why the attribute-conversion route was tried. In this case, there is an attempt to convert Calendar to ZoneDateTime.
I had seen this in another message noting:
Add #Convert(converter=OracleZonedDateTimeSeriliazer.class) on top of
your createdOn attribute on ur Entity class.
But, as mentioned above, Calendar is being used as part of the entity and not ZonedDateTime
the way the entity class is defined now. Before (when using the ( convDateStrWithZoneTOCalendar above), the "#Convert" items were not present
#Entity
#Table(name = "LAWNCORRJOB", schema = "ORAAPPS", uniqueConstraints = #UniqueConstraint(columnNames = {
"TENANTID", "GENERATEDJOBNO" }))
public class Lawncorrjob implements java.io.Serializable {
private static final long serialVersionUID = -8207025830028821136L;
....
#Convert( converter = OracleCalendarZoneDateTimeSerializer.class, disableConversion = false )
private Calendar schedfirstdayts;
#Convert( converter = OracleCalendarZoneDateTimeSerializer.class, disableConversion = false )
private Calendar schedlastdayts;
...
}
the converter being used: converts Calendar to ZonedDateTime (under Oracle)
#Converter(autoApply = true)
public class OracleCalendarZoneDateTimeSerializer implements
AttributeConverter<Calendar, ZonedDateTime> {
#Override
public ZonedDateTime convertToDatabaseColumn(Calendar attribute) {
if (attribute == null)
return null;
// get the timezone
TimeZone tz = attribute.getTimeZone();
// use the timezone to specify the area location
// ex: For example, TimeZone.getTimeZone("GMT-8").getID() returns
// "GMT-08:00".
ZonedDateTime xzdt = ZonedDateTime.of(attribute.get(Calendar.YEAR),
attribute.get(Calendar.MONTH),
attribute.get(Calendar.DAY_OF_MONTH) + 1,
attribute.get(Calendar.HOUR_OF_DAY),
attribute.get(Calendar.MINUTE), attribute.get(Calendar.SECOND),
attribute.get(Calendar.MILLISECOND), ZoneId.of(tz.getID()));
return xzdt;
}
#Override
public Calendar convertToEntityAttribute(ZonedDateTime dbData) {
GregorianCalendar newcal = DateTimeUtils.toGregorianCalendar(dbData);
return newcal;
}
}
But, when executing this code, I get an error:
Error Message: Could not commit JPA transaction; nested exception is
javax.persistence.RollbackException: Error while committing the
transaction CAUSE : javax.persistence.RollbackException: Error while
committing the transaction",
So, is there any way I can fix either option to get this all working?
Any help, hints or advice is appreciated.
TIA
Given this Entity I need to post the new Object of type Contracts. I
http://www.springframework.org/tags/form tag form/sf. I also got jquery datapicker. The problem I have got is datapicker returns a String not Date object. How can it be parsed? The only solution I think will work is to get date from datepicker as #RequestParam in the #Controller class and parse it as a java.util.Date object.
#Entity
#Table(name = "contract")
public class Contracts {
#Id
#Column(name = "contract_id")
private int contractId;
#Column(name = "date_added")
private Date creationDate;
#Column(name = "date_start")
private Date startDate;
#Column(name = "date_end")
private Date finishDate;
#NotNull
#Column(name = "payment_amount")
private Integer paymentAmount;
#Column(name = "payment_type")
#Enumerated(EnumType.STRING)
private PaymentType paymentType;
private boolean valid;
#ManyToOne
#JoinColumn(name = "system_id")
private Systems system;
And this is 'POST' part of my Controller class.
#RequestMapping(value = "/createcontract", method = RequestMethod.POST)
public String createContract(#ModelAttribute("contract") #Valid final Contracts contract, BindingResult results,
#RequestParam("system-id") int systemId) {
if(results.hasErrors())
return "newcontract";
return "redirect:contracts";
Another question (because I tagged postgresql) is whether is 'all-right' to store java.util.Data object in postgresql as just date or maybe I should store it as 'timestamp with time zone'?
jQuery UI DatePicker gives Date object
The plugin allows you to obtain a Date object using getDate method.
Here is a Plunker with a working example.
$(function() {
$('#datePicker').datepicker();
$('#datePicker').on('change', () => {
let date = $('#datePicker').datepicker('getDate');
alert(`Date ${date} is ${date instanceof Date ? 'a Date object' : 'not a Date object'}`);
});
});
Date type - JPA to PostgreSQL mapping
Use timestamp with time zone in PostgreSQL
Usually is best to keep your dates as UTC in your database. This will give the most flexibility as you can represent the date in whichever zone you desire. This translates into using the timestamp with time zone as a type which will store as UTC. This means that your date time, before being stored, is added the zone offset in order to obtain the UTC.
Set the timezone to UTC of your JVM or your JPA provider
Is important that all your dates are expressed as UTC and not in a specific time zone. And when these are sent via the wire to your database the session needs to have the UTC time zone.
This means that the timezone needs to be UTC on JVM or JPA provider (eg: Hibernate).
As explained in this blog you can set UTC by:
JVM: java -Duser.timezone=UTC -jar blabla.jar
Or by
JVM: TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));
Or by
Hibernate: (application.properties) spring.jpa.properties.hibernate.jdbc.time_zone = UTC
Check which version works for you.
Persisting Date field
Therefore your field can be expressed as:
#Column(name = "date_added", columnDefinition = "TIMESTAMP WITH TIMEZONE")
#Temporal(TemporalType.TIMESTAMP)
private Date creationDate;
And you need to ensure that the Date object represents a date time in UTC.
Useful mappings
You can store your Date object in PostgreSQL as:
timestamp with or without timezone
time with or without timezone
date
Using the JPA annotation #Temporal applied on your Date field you can specify how the object is being mapped:
#Temporal(TIMESTAMP) to timestamp
#Temporal(DATE) to date
#Temporal(TIME) to time
Also specifying that your column is timestamp with timezone can be stated using annotation #Column(columnDefinition = "TIMESTAMP WITH TIMEZONE").
import java.sql.Timestamp;
oR
import java.sql.Date;
add this import ur pojo .
I have problems to get the full DATE info from my Oracle DB (dd/mm/yyyy hh/mm/ss).
In the db level, in the column that I want to receive I set test values:
update my_table
set my_date_column=(to_date('2011-06-15 15:43:12', 'yyyy-mm-dd hh24:mi:ss'));
but in my JPA entity I have:
#Column(name = "MY_DATE_COLUMN")
#Temporal(TemporalType.DATE)
private Date dateDetailed;
public Date getDateDetailed() {
if (this.dateDetailed!= null) {
return this.dateDetailed;
}
return null;
}
public void setDateDetailed(Date dateDetailed) {
if (dateDetailed!= null) {
this.dateDetailed= dateDetailed;
} else {
this.dateDetailed= null;
}
}
Each time I acccess my object, It is giving me date without hours, min and seconds.
I tried to use TemporalType.TIMESTAMP, but in that case I would need to also change column type in db (which I want to avoid).
Any suggestions?
Its the TemporalType.DATE
You will need TIME or TIMESTAMP. DATE is only the date without time. TIMESTAMP is represented as a number.
By using the TIMESTAMP temporal type, you will get the date and the time part of the java date datatype but Oracle will make a column with the TIMESTAMP datatype. To overcome this issue if you want a DATE datatype, you can use the columnDefinition parameter of the column annotation such as:
#Column(name = "MY_DATE_COLUMN", columnDefinition = "DATE")
#Temporal(TemporalType.TIMESTAMP)
private Date dateDetailed;