简体   繁体   中英

How should i manage Sessions and Transactions in hibernate?

I have a function that has some nested if statements and a query in each of the if statements ,how should i manage transaction and session calls.I know that i should bind each call with seperate transaction .

Session session=null;
Transaction tx=null;
if(!list.isEmpty()){
    session=factory.openSession();
    tx=session.beginTransaction();
    session.createQuery(" update Tbluser set loggedStatus='9'").executeUpdate();
    tx.commit();
    session.close();
    if(list.get(1)=="N")
    {
        ///some query
    }
}

should i have not closed the session just yet or should i create a new Session object for the new query that i have? or what else should be the correct approach?

If all the operations in the if blocks are related and atomic, you should consider opening one session and transaction before the first if block and commit/close after the last if block.

If each operations is separate, then you can open one session before the first if and enclose each if in a new transaction.

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