简体   繁体   中英

Spring Repositories and DATA_FORMAT with nativeQuery=false

I am trying do something super simple but with Spring Repositories somethings is a bit hard. Basically I wanted to group by with DATE_FORMAT, example:

 @Query("SELECT " +
             "    new users.bridge.models.dto.PerformanceDTO(sum(t.gl), sum(t.gl)) " +
             "FROM " +
             "    Transaction t " +
             "GROUP BY DATA_FORMATE(t.createdDate,'%Y-%m-%d')")

But it throws a syntax error. Is there a way to do that with spring repositories? I don't want to use nativeQuery=true flag, otherwise I can not use this syntax

new gara.users.bridge.models.dto.PerformanceDTO(sum(t.gl), sum(t.gl))

UPDATE:

The erros are: 在此处输入图片说明

all the java stack is quite big but:

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: asc near line 1, column 180 [SELECT     new gara.users.bridge.models.dto.PerformanceDTO(sum(t.gl), sum(t.gl),t.createdDate) FROM     gara.model.db.Transaction t GROUP BY DATE_FORMAT(t.createdDate,'%Y-%m-%d') asc] 

If you specify nativeQuery=false (the default) you need to use valid JPQL. JPQL doesn't know the function DATE_FORMAT but you can use the generic FUNCTION function which allows you to call arbitrary SQL functions.

So a group by clause like this should work: GROUP BY FUNCTION('DATA_FORMAT', t.createdDate,'%Y-%m-%d')

Just be aware that such queries aren't portable between databases.

but with Spring Repositories somethings is a bit hard.

You can always fall back on custom method implementations which shouldn't be much harder than implementing your repository yourself in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM