如何在Hibernate中使用Mysql变量? [英] How to use Mysql variables with Hibernate?
问题描述
但是hibernate会抛出一个错误:在参数前缀
所以和= = mysql变量赋值和hibernate变量赋值有冲突。
这里是我的sql查询:
SET @rank:= 0;
UPDATE Rank SET Rank_Level = @ rank:= @ rank + 1 ORDER BY Level;
hibernate代码(jpa语法):
查询查询= em.createNativeQuery(theQuery);
query.executeUpdate();
我无法使用存储过程,因为我的sql查询是动态生成的('Level'可以是'int'或'force'...)
我该怎么做?
谢谢
我最终使用存储过程(是的,我最初不想)创建动态查询(我不是)这是我的代码:
存储过程:
DELIMITER |
如果存在UpdateRank |则删除程序
CREATE PROCEDURE UpdateRank(IN shortcut varchar(30))
BEGIN
SET @ rank = 0;
SET @ query = CONCAT('UPDATE Rank SET',快捷键,'= @ rank:= @ rank + 1 ORDER BY',快捷键);
PREPARE q1 FROM @query;
EXECUTE q1;
DEALLOCATE PREPARE q1;
END;
|
DELIMITER;
提示是使用CONCAT函数在存储过程中动态创建一个查询。然后,在经典的hibernate函数中调用该过程:
$ $ $ $ $ $ $ $>查询q =
$ b
em.createNativeQuery(CALL updateRank('lvl'));
q.executeUpdate();
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 there is a conflict with the := mysql variable assignment and hibernate variable assignment.
Here is my sql query:
SET @rank:=0;
UPDATE Rank SET rank_Level=@rank:=@rank+1 ORDER BY Level;
the hibernate code (jpa syntax):
Query query = em.createNativeQuery(theQuery);
query.executeUpdate();
I can't use a stored procedure because my sql query is dynamically generated ('Level' can be 'int' or 'force'...)
How can I do this ?
thanks
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();
这篇关于如何在Hibernate中使用Mysql变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!