Search code examples
javasqldatetimenativequery

Java - set currentDate time in Native Query?


I have the following field in my entity:

@JsonProperty
@Column(name = "updated")
@Temporal(TemporalType.TIMESTAMP)
private Calendar updated;

I have the following Native query where I am trying to set the update date above:

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String updatedDate = dateFormat.format(Calendar.getInstance().getTime());
    
String queryString = "update " + "persons" +
                     " set updated = " + updatedDate" +
                     " where person_id = 1";

But I am getting an error saying incorrect datetime value.

How can I set the value? It is datetime in the db.


Solution

  • If you are really doing a raw JDBC update query, then you should be using a prepared statement here:

    String sql = "UPDATE persons SET updated = ? WHERE person_id = 1";
    PreparedStatement ps = conn.prepareStatement(sql);
    java.util.Date date = Calendar.getInstance().getTime();
    java.sql.Date sqlDate = new java.sql.Date(date.getTime());
    ps.setDate(1, sqlDate);
    int numRowsAffected = ps.executeUpdate();
    

    But you might want to consider migrating away from using Calendar, as it has been replaced by a new suite of date/time functions in Java 8. Instead, consider replacing Calendar with LocalDateTime.