Hibernate不通过本机查询更新值

时间:2018-05-22 10:11:42

标签: mysql hibernate sql-update nativequery

亲爱的stackoverflow社区,

我不确定为什么下面的代码不会更新我的数据库数据,但是从hibernate日志中获取查询似乎有效......

我正在使用Hibernate 5.2.12.Final

这是我的全部功能:

    EntityManager em = Utils.initEntityManager();
    em.getTransaction().begin();

    em.persist(receptacle);

    em.createNativeQuery("UPDATE product_item pi"
            + " JOIN ereturn er ON pi.ereturn = er.id "
            + "SET pi.receptacle = :receptacle "
            + "WHERE pi.returnAction = :returnAction "
            + "AND er.destination = :destination "
            + "AND er.status = 'RECEIVED'")
            .setParameter("receptacle", receptacle.getId())
            .setParameter("returnAction", receptacle.getReturnAction())
            .setParameter("destination", receptacle.getDestination().getId())
            .executeUpdate();       

    em.getTransaction().commit();
    em.close();

这是来自hibernate的日志

19:47:29,048 DEBUG [org.hibernate.SQL] - 
    UPDATE
        product_item pi 
    JOIN
        ereturn er 
            ON pi.ereturn = er.id 
    SET
        pi.receptacle = ? 
    WHERE
        pi.returnAction = ? 
        AND er.destination = ? 
        AND er.status = 'RECEIVED'
Hibernate: 
    UPDATE
        product_item pi 
    JOIN
        ereturn er 
            ON pi.ereturn = er.id 
    SET
        pi.receptacle = ? 
    WHERE
        pi.returnAction = ? 
        AND er.destination = ? 
        AND er.status = 'RECEIVED'
19:47:29,049 TRACE [org.hibernate.type.descriptor.sql.BasicBinder] - binding parameter [1] as [BIGINT] - [20]
19:47:29,049 TRACE [org.hibernate.type.descriptor.sql.BasicBinder] - binding parameter [3] as [BIGINT] - [148375]
19:47:29,049 TRACE [org.hibernate.type.descriptor.sql.BasicBinder] - binding parameter [2] as [VARBINARY] - [RETURNTOCLIENT]

我从日志中获取相同的查询,替换参数并在我的mysql控制台中运行...查询有效!​​!!

问题:为什么mysql在上面的更新查询运行时没有改变任何数据?

非常感谢

1 个答案:

答案 0 :(得分:0)

问题是returnAction字段是一个枚举,所以我必须将它转换为String。

奇怪的是,冬眠并没有抱怨......

这个修复:

em.createNativeQuery("UPDATE product_item pi"
            + " JOIN ereturn er ON pi.ereturn = er.id "
            + "SET pi.receptacle = :receptacle "
            + "WHERE pi.returnAction = :returnAction "
            + "AND er.destination = :destination "
            + "AND er.status = 'RECEIVED'")
            .setParameter("receptacle", receptacle.getId())
            .setParameter("returnAction", receptacle.getReturnAction().toString())
            .setParameter("destination", receptacle.getDestination().getId())
            .executeUpdate();