Search code examples
hibernatejpakotlincriteria

JPA + Hibernate currentTimestamp() did not match expected type


I have the following code that throws java.lang.IllegalArgumentException: Parameter value [org.hibernate.query.criteria.internal.expression.function.CurrentTimestampFunction@30cb223b] did not match expected type [java.util.Date (n/a)]

@Transactional
open fun delete(entity: E) {
    val cb = em.criteriaBuilder

    // create update query
    val query = cb.createCriteriaUpdate(Entity::class.java)
    val updateEntity = query.from(Entity::class.java)

    // set update and where clause
    query.set("deletedOn", cb.currentTimestamp()) // <- problem exhibited due to this line
    query.where(cb.equal(updateEntity.get<Long>("id"), entity.id))

    // perform update
    em.createQuery(query).executeUpdate()
}

The error is due to when I use CriteriaBuilder's currentTimestamp(). In Hibernate's QueryParameterBindingValidator in validate(Type paramType, Object bind, TemporalType temporalType) there's this line

final Class parameterType = paramType.getReturnedClass();

The entity's deletedOn is of type Timestamp. paramType refers to that field and is of type TimestampType (coming from Hibernate). When getReturnedClass() is called, it returns java.util.Date (I guess because that's the base type?). Unfortunately then the type mismatch occurs with the expression cb.currentTimestamp() and the error is thrown.

I could not find a working example online of how to use currentTimestamp() from CriteriaBuilder to achieve this task.

Any help would be appreciated! Thanks!


Solution

  • I found that using this line will make it work.

    query.set(updateEntity.get<Timestamp>("deletedOn"), cb.currentTimestamp())