0

I have a mysql query like this to get the row numbers.

set @rank = 0; 
select @rank := @rank + 1 as rank,id,name from test

In hibernate 3 ':=' was a problem.

session.createSQLQuery("set @rank = 0; 
                        select @rank := @rank + 1 as rank,id,name from test");

i switch to hibernate 3 to 4 and used escape character.

session.createSQLQuery("set @rank = 0; 
                        select @rank \\:= @rank + 1 as rank,id,name from test");

Now another exception occured. It gives the exception:

"Parameter rank does not exist as a named parameter" 

I tried this:

 session.createSQLQuery("select :rank \\:= :rank + 1 as rank,
                         ID,NAME,SURNAME from test").setInteger("rank", 0)

This time it gives this exception:

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

Any idea how can i solve this issue?

2 Answers 2

1

While using doReturningWork() you gain the access to the plain JDBC connection. Then you should split your SQL into 2 executions (set and select):

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;
  }
});
Sign up to request clarification or add additional context in comments.

Comments

0

Hibernate doesn't support database specific SQL syntaxes or SQL local variables.

From what I see you don't even want to select some entity, so you just need an aggregation query:

select count(t), t.id, t.name 
from Test t
group by t.id, t.name

Assuming you have a Test entity mapped to the test table.

5 Comments

Are you sure there is no way using local variables with hibernate? This is sad.
You can always use native SQL, even with Hiberante so you can give that a try.
I dont understand you. I think i was using native SQL with "createSQLQuery". Can you explain your comment a little bit please?
Check doWork to get access to the current Connection, where you can write plain old JDBC.
i tried doReturningWork() still doesnt let me to use local sql variable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.