How to use Mysql variables with Hibernate?

后端 未结 3 1959
北荒
北荒 2020-12-11 09:40

I need to use a native sql query in Hibernate with use of variable.

But hibernate throws an error saying: Space is not allowed after parameter prefix

So ther

相关标签:
3条回答
  • 2020-12-11 10:19

    I'll copy paste my answer from https://stackoverflow.com/a/25552002/3987202

    Another solution for those of us who can't make the jump to Hibernate 4.1.3.
    Simply use /*'*/:=/*'*/ inside the query. Hibernate code treats everything between ' as a string (ignores it). MySQL on the other hand will ignore everything inside a blockquote and will evaluate the whole expression to an assignement operator.
    I know it's quick and dirty, but it get's the job done without stored procedures, interceptors etc.

    0 讨论(0)
  • 2020-12-11 10:21

    Use MySQL Proxy to rewrite the query after Hibernate has sent the query to the database.

    For example supply Hibernate with this,

    UPDATE Rank SET rank_Level=incr(@rank) ORDER BY Level;
    

    but rewrite it to this,

    UPDATE Rank SET rank_Level=@rank:=@rank+1 ORDER BY Level;
    
    0 讨论(0)
  • 2020-12-11 10:27

    Well, I finally use stored procedure (yes, what I don't want initially) to create dynamic query (I don't think it was possible).

    Here is my code: The stored procedure:

    DELIMITER |
    
    DROP PROCEDURE IF EXISTS UpdateRank |
    
    CREATE PROCEDURE UpdateRank(IN shortcut varchar(30))
    BEGIN
        SET @rank=0;
        SET @query=CONCAT('UPDATE Rank SET ', shortcut, '=@rank:=@rank+1 ORDER BY ', shortcut);     
    
        PREPARE q1 FROM @query;
        EXECUTE q1;
        DEALLOCATE PREPARE q1;
    END;
    
    |
    DELIMITER ;
    

    The tip is the use of the CONCAT function to dynamically create a query in the stored procedure.

    Then, call the procedure in classic hibernate function:

    Query q = em.createNativeQuery("CALL updateRank('lvl')");
    q.executeUpdate();
    
    0 讨论(0)
提交回复
热议问题