使用JPQL/JPA时如何使用date_format [英] How to use date_format when using JPQL/JPA
问题描述
我正在使用MySQL作为数据库进行Java EE,并在我的代码上实现JPA.
I am doing Java EE with MySQL as database and implementing JPA on my codes.
我从MySQL Workbench检索数据没有问题,但是当我将语法更改为JPQL时,它不起作用.
I have no problem retrieving the data from MySQL Workbench but when I change my syntax to JPQL's it does not work.
例如在MySQL中-有效
For e.g. in MySQL - it works
SELECT date_format(s.date,'%Y, %m, %d') from Transactions s;
在JPQL中-不会
SELECT date_format(s.date,'%Y, %m, %d') from TransactionEntity s;
如何修改以适合JPA查询?
How do i modify to suit the JPA query?
注意: 在JPQL中,以下工作
Note: in JPQL the following works
SELECT s.date from TransactionEntity s;
正如任何文档所告诉的那样,
推荐答案
SQL函数date_format
不是JPQL的一部分,所以不要认为仅将SQL推入JPQL并期望它的工作.
SQL function date_format
is not part of JPQL, as any documentation would tell you, so don't see the point in just pushing SQL into JPQL and expecting it to work.
您可以使用JPA 2.1进行以下操作
What you can do with JPA 2.1 is invoke it as follows
function("date_format", s.date, '%Y, %m, %d')
其中,function
是调用任何本机SQL函数的一种方式.显然,这意味着您失去了数据库独立性,因为该功能并非在所有数据存储上都有效.
where function
is a way to invoke any native SQL function. This clearly means you lose database independence because that function is not valid on all datastores.
这篇关于使用JPQL/JPA时如何使用date_format的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!