The trick is to do the string to date conversion in Java.
@Transactional
public void insertWithQuery(String id, String firstName, String lastName,
String lastSeen) {
// 'Wed Jan 01 02:00:00 IST 2020'
DateTimeFormatter formatter =
DateTimeFormatter.ofPattern("EEE LLL dd HH:mm:ss zzz yyyy");
java.time.ZonedDateTime dateTime =
ZonedDateTime.parse(lastSeen, formatter);
entityManager.createNativeQuery(
"INSERT INTO person (id, first_name, last_name, birth_date) " +
"VALUES (?,?,?,?)")
.setParameter(1, id)
.setParameter(2, firstName)
.setParameter(3, lastName)
.setParameter(4, dateTime)
.executeUpdate();
}
Note: this code is not tested. You may need to tweak the formatter's pattern. (I am going from what I think the javadoc says.)
The datetime stamp is stored in an SQL database in a format-independent way. By using setParameter
you avoid having to convert the date into a text format that the native SQL dialect expects. Hibernate / JPA takes care of it.