我有一个相当奇怪的问题。我有本机查询,在sql server上执行时运行得很好:
SELECT date_time, GREATEST(sum(count_up - count_down) OVER (PARTITION BY date_trunc('day', result.date_time) ORDER BY date_time),0) AS cum_amt FROM peoplecounting.result order BY date_time;
但是,在JPA中将此查询用作本机查询会导致语法错误
@NamedNativeQueries({@NamedNativeQuery(
name = "Result.getTotal",
query = "SELECT date_time, GREATEST(sum(count_up - count_down) OVER (PARTITION BY date_trunc('day', peoplecounting.result.date_time) ORDER BY date_time),0) AS cum_amt FROM peoplecounting.result order BY date_time;")})
public class Result implements Serializable {...
///
@Entity
@SqlResultSetMapping(name = "TotalResultMapping", entities = {@EntityResult(entityClass = TotalResult.class, fields = {@FieldResult(name = "total", column = "cum_amt"), @FieldResult(name = "date", column = "date_time")})})
public class TotalResult {
private static final long serialVersionUID = 1L;
public TotalResult() {
}
@Id Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getTotal() {
return total;
}
public void setTotal(Integer total) {
this.total = total;
}
Integer total;
}
致电:em.createNativeQuery("Result.getTotal","TotalResultMapping").getResultList();
我明白了:
INFO [stdout] (default task-44) Hibernate: Result.getTotal
WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-44) SQL Error: 0, SQLState: 42601
ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-44) Error: Syntax error at or near "Result"
答案 0 :(得分:1)
所以问题是em.createNativeQuery(...)
不是NamedNativeQuery
的正确调用,为了做到这一点,我应该调用em。createNamedQuery(...)
。但是,如果看到em.createNativeQuery(...)
不接受@SqlResultSetMapping
,则很难将结果映射到自定义类。
最终解决方案是使用
return em.createNativeQuery("SELECT peoplecounting.result.date_time, GREATEST(sum(peoplecounting.result.count_up - peoplecounting.result.count_down) " +
"OVER (PARTITION BY date_trunc('day', peoplecounting.result.date_time) " +
"ORDER BY peoplecounting.result.date_time),0) AS cum_amt" +
" FROM peoplecounting.result" +
" order BY peoplecounting.result.date_time",
"TotalResultMapping").getResultList();
这样我可以使用我的@SqlResultSetMapping
,一切都很好。
答案 1 :(得分:0)
SQLState
是42601,这是语法错误。
尝试删除命名本机查询声明末尾的分号。虽然在数据库本身发出查询时使用分号,但分号不是查询本身的一部分。
因此,这可能有效(未经过测试,但当您尝试将分号添加到普通JDBC查询时,Oracle会遇到类似的问题):
@NamedNativeQueries({@NamedNativeQuery(
name = "Result.getTotal",
query = "SELECT date_time, GREATEST(sum(count_up - count_down) OVER (PARTITION BY date_trunc('day', peoplecounting.result.date_time) ORDER BY date_time),0) AS cum_amt FROM peoplecounting.result order BY date_time")})