简体   繁体   中英

Hibernate: updating an object in a different Session?

Is it bad practice in Hibernate to update an Object in a different Session than it was originally created in? I think the answer is yes, because a Hibernate Session (by default) will cache its Session Objects, and release them when the Session is closed or the Object is evicted. So creating an Object in one Session then updating it in another Session (while the Object is still 'alive' in the first Session) seems like bad practice to me. Can anyone explain why, what are the repercussions? For example, consider this code (which is shortened for clarity):

private void updateRequest(Request req){ //Request came from another Hibernate Session
        MyDAO myDB = null;
        myDB = new MyDAO();
            Transaction trans = myDB.getSession().beginTransaction();
            myDB.getSession().update(object);
            trans.commit();
    }

This is called "Session per operation anti-pattern", here is a quote from hibernate documentation that better explains the issue:

Do not use the session-per-operation antipattern: do not open and close a Session for every simple database call in a single thread . The same is true for database transactions. Database calls in an application are made using a planned sequence; they are grouped into atomic units of work. This also means that auto-commit after every single SQL statement is useless in an application as this mode is intended for ad-hoc SQL console work. Hibernate disables, or expects the application server to disable, auto-commit mode immediately. Database transactions are never optional. All communication with a database has to occur inside a transaction. Auto-commit behavior for reading data should be avoided, as many small transactions are unlikely to perform better than one clearly defined unit of work. The latter is also more maintainable and extensible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM