Search code examples
mysqlhibernatesql-updatenativequery

Hibernate not updating values through a native query


Dear stackoverflow community,

I am not sure why the code below does not update my database data, however taking the query from the hibernate logs seems to work...

I am using Hibernate 5.2.12.Final

This is my whole function:

    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();

And this is the log from 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]

I take same query from the logs, replace the parameters and run it in my mysql console... the query works!!!

QUESTION: why mysql is not changing any data when the update query above runs?

thank you very much


Solution

  • the issue was returnAction field is an enum so I have to convert it to String.

    Weird thing is that hibernate didn't complain...

    This the fix:

    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();