Is it possible to detach Hibernate entity, so that changes to object are not automatically saved to database?

前端 未结 5 1241
野性不改
野性不改 2020-11-30 00:12

I have Hibernate entity that I have to convert to JSON, and I have to translate some values in entity, but when I translate values, these values are instantly saved to datab

5条回答
  •  北荒
    北荒 (楼主)
    2020-11-30 01:03

    You can also avoid that your entities are attached to the Hibernate Session by using a StatelessSession:

    StatelessSession session = sessionFactory.openStatelessSession();
    

    instead of

    Session session = sessionFactory.getCurrentSession();
    

    Note that you must take care yourself of closing the StatelessSession, unlike the regular Hibernate Session:

    session.close(); // do this after you are done with the session
    

    Another difference compared to the regular Session is that a StatelessSession can not fetch collections. I see it's main purpose for data-fetching-only SQLQuery stuff.

    You can read more about the different session types here:

    http://www.interviewadda.com/difference-between-getcurrentsession-opensession-and-openstatelesssession/

提交回复
热议问题