我有一个像这样的mysql查询来获取行号。
set @rank = 0;
select @rank := @rank + 1 as rank,id,name from test
在休眠3':='是一个问题。
session.createSQLQuery("set @rank = 0;
select @rank := @rank + 1 as rank,id,name from test");
我切换到休眠3到4并使用转义字符。
session.createSQLQuery("set @rank = 0;
select @rank \\:= @rank + 1 as rank,id,name from test");
现在发生了另一个例外。它给出了例外:
"Parameter rank does not exist as a named parameter"
我试过了:
session.createSQLQuery("select :rank \\:= :rank + 1 as rank,
ID,NAME,SURNAME from test").setInteger("rank", 0)
这次它给出了这个例外:
You have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near ':= 0 + 1 as rank,id,
name from test' at line 1
我知道如何解决这个问题?
答案 0 :(得分:1)
使用doReturningWork()时,您可以访问普通的JDBC连接。 然后你应该将SQL分成2个执行(设置和选择):
final Object queryResultObject = session.doReturningWork(new ReturningWork<ReturnObjectType>() {
@Override
public ReturnObjectType execute(Connection connection) throws SQLException {
final Statement statement = connection.createStatement();
statement.execute("set @rank = 0");
final ResultSet resultSet = statement.executeQuery(
"select @rank := @rank + 1 as rank,id,name
from test");
ReturnObjectType result = /* transform ResultSet into return value */
return result;
}
});
答案 1 :(得分:0)
Hibernate不支持特定于数据库的SQL语法或SQL局部变量。
从我看到你甚至不想选择某个实体,所以你只需要一个聚合查询:
select count(t), t.id, t.name
from Test t
group by t.id, t.name
假设您有一个Test实体映射到测试表。