【问题标题】:What is the best way to set a MySQL user variable in a Java, Spring MVC, Hibernate with Annotations web application?在 Java、Spring MVC、Hibernate with Annotations Web 应用程序中设置 MySQL 用户变量的最佳方法是什么?
【发布时间】:2011-04-22 02:27:45
【问题描述】:

我需要能够设置一个 MySQL 用户变量,该变量在 Spring MVC Hibernate Web 应用程序的触发器中使用。这个用户变量在被 Hibernate 操作的表上的 MySQL 触发器中使用。我需要在 Hibernate 对数据库的所有写访问期间正确设置此用户变量。

不幸的是,HQL 没有设置 MySQL 用户变量的技术,而且我找到的直接执行 MySQL 的方法似乎不适用于事务。由于用户变量的生命周期是数据库连接的生命周期,因此我需要 MySQL 使用与执行 HQL 相同的连接来执行。但是,在执行本机 MySQL 之后,我的事务似乎运行 HQL,因此 MySQL 触发器不存在预期的用户变量。

要执行我一直在使用的原生 MySQL 查询:

HibernateEntityManager em=(HibernateEntityManager) getEntityManager();
Connection connection=em.getSession().connection();
Statement s = connection.createStatement();
s.executeUpdate("SET @current_user_id="+userId);

当 Spring MVC 提交我的事务时,它会运行 HQL 查询,然后抛出异常,因为 @current_user_id 导致 MySQL 触发器中断。我通过在不存在触发器的情况下进行测试来验证这一点。

【问题讨论】:

    标签: java mysql hibernate web-applications spring-mvc


    【解决方案1】:

    我发现这个问题与我的非常相似:How to use Mysql variables with Hibernate?

    所以我按照建议使用了存储过程和实体管理器上的 executeNativeQuery 方法来调用它。

    这是我的存储过程代码:

    DROP PROCEDURE IF EXISTS set_current_user
    CREATE PROCEDURE set_current_user(IN user_id BIGINT)
    BEGIN
      SET @current_user_id = user_id
    END
    

    我称之为:

    Query q = em.createNativeQuery("CALL set_current_user("+userId+")");
            q.executeUpdate();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多