0

I have following method to extract data from DB table

    public User getNextUser() {
            final EntityManager em = getEntityManagerFactory().createEntityManager();

            final String sql = "UPDATE user " +
                    "SET processing = TRUE " +
                    "WHERE id = (" +
                                "SELECT id " +
                                "FROM user  " +
                                "WHERE processing = FALSE " +
                                "LIMIT 1 FOR UPDATE) " +
                    "RETURNING *";

            final Query query =  em.createNativeQuery(sql, User.class);
            User result = null;

            try {
                List userList = query.getResultList();
                if (!userList.isEmpty()) {
                    result = (User) userList.get(0);
                }
            } finally {
                em.close();
            }
            return result;
}

How it's possible to convert this native query to Hibernate query (to not invalidate 2nd level cache)? I have read that equivalent of

SELECT ... FOR UPDATE

in Hibernate it's possible to implement via

PESSIMISTIC_WRITE

Luigi Saggese
  • 5,299
  • 3
  • 43
  • 94
  • [This question](http://stackoverflow.com/questions/23436546/hibernate-criteira-query-select-for-update-order-by) has nothing to do with yours, but includes a good example of `SELECT FOR UPDATE` with hibernate – BackSlash Jul 28 '14 at 07:00
  • 1
    @BackSlash thanks, i have understand about SELECT FOR UPDATE, but not for UPDATE part in my case. – Luigi Saggese Jul 28 '14 at 07:44

0 Answers0