Search code examples
javasqlhibernatesql-update

Hibernate update without select


I've a question on hibernate operation: update.

Here a bit of code:

Campaign campaign = campaignDAO.get(id);
campaign.setStatus(true);
campaignDAO.update(campaign);

If I just have all the data of the campaign object, is there any way to perform an update without performing the select (campaignDAO.get(id)) first?

Thanks,

Alessio


Solution

  • HQL will definitely help you.

    In order to maintain the separation of concerns, you can add a more specialized method in you DAO object:

    public void updateStatusForId(long id, boolean status){
    //provided you obtain a reference to your session object
    session.createQuery("UPDATE Campaign SET status = " + status + " WHERE id = :id").setParameter("id", id).executeUpdate();
    //flush your session
    }
    

    Then you could simply call this method from your business method. You can check the generated SQL statements inside the logs of your app by setting the show_sql hibernate property to true.