Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate time with JPA or native query

I want to use Hibernate current_timestamp() to write a timestamp based on the database time to a column. I want to use the database time, not the system time of the system of my service that uses the database. I am using the database time for two queries, Lock and Unlock.

Lock query

UPDATE MyEntity e SET e.lock = current_timestamp() WHERE e.id = :id

Unlock query

UPDATE MyEntity e SET e.lock = (current_timestamp() - "30 seconds") WHERE e.id = :id

My last resort is to use a native query for PostgreSQL like this:

SELECT CURRENT_TIMESTAMP < (CURRENT_TIMESTAMP + INTERVAL '30 second')

I am unable to locate the documentation on how to add/subtract time,if it is even supported. How can I build the Unlock query?

like image 644
span Avatar asked Dec 15 '17 16:12

span


People also ask

How do I use JPA with spring data?

At runtime, Spring Data JPA then generates a class that implements that interface. You can then use that interface as the return type of a repository method. To assign a native query to that method, you need to annotate it with @Query, provide the native SQL statement, and set the native attribute to true.

Does JPA have its own query language like JPQL?

Of course not! JPA has its own query language but it also supports native SQL. You can create these queries in a very similar way as JPQL queries and they can even return managed entities if you want. Creating a dynamic native query is quite simple.

What is the difference between native and positional parameters in JPA?

JPQL and native SQL queries use the same Query interface which provides a setParameter method for positional and named parameter bindings. But the use of named parameter bindings for native queries is not defined by the JPA specification. Positional parameters are referenced as “ ?” in your native Query and their numbering starts at 1.

How do you map a query result set in JPA?

You can reference an @SqlResultSetMapping in the definition of your @NamedNativeQuery. The mapping gets automatically applied to the result set when you instantiate and execute the query. That’s also the case when Spring Data JPA executes this query when you call the corresponding repository method.


1 Answers

set the default value of the column to the (your database specific) currenttime value. With MySql, the column would look like this:

column_name DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP

Edit

Here is an example (MySql) that will update the datetime column every time the row is updated:

last_update DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
like image 200
DwB Avatar answered Sep 24 '22 05:09

DwB