JPA Criteria API: how to retrieve date in “mm/dd/yyyy” format

流过昼夜 提交于 2019-12-08 18:30:36

Criteria API defines function expression to execute native SQL functions in the CriteriaBuilder interface as follows:

<T> Expression<T> function(String name, Class<T> type, Expression<?>... args);

where name is the name of the SQL function, type is the expected return type and args is a variable list of arguments (if any).

Here is an example how to use it in a Criteria query:

CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery cq = cb.createQuery(String.class);
Root<RadExamTimes> root = cq.from(RadExamTimes.class);
cq.select( cb.function("to_char", String.class, root.get("begin_exam"), cb.literal("MM/DD/YYYY")));

TypedQuery<String> query = entityManager.createQuery(cq);
List<String> result = query.getResultList();

where

  • RadExamTimes: a hypothetical root entity
  • MM/DD/YYYY: a database-specific format (in this example Postgresql date format; for Oracle use Ora format, etc)
  • to_char: Postgresql function to convert date value to string
  • begin_exam: the date field to be formatted

The format string cannot be passed as is so that the literal() method is used to wrap it.

Note: The above example is tested on MySQL database with MySQL function and corresponding date format; but the example changed to match Postgresql syntax.

Viplove Gujrathi
SELECT '2001-02-16 20:38:40'::date;

date
----------------
2001-02-16
(1 row)

Or you can use @TemporalType on JPA entity field.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!