Example usage for org.hibernate Transaction setTimeout

List of usage examples for org.hibernate Transaction setTimeout

Introduction

In this page you can find the example usage for org.hibernate Transaction setTimeout.

Prototype

void setTimeout(int seconds);

Source Link

Document

Set the transaction timeout for any transaction started by a subsequent call to #begin on this instance.

Usage

From source file:br.gov.jfrj.siga.model.dao.HibernateUtil.java

License:Open Source License

public static void iniciarTransacao() {

    // bruno.lacerda@avantiprima.com.br
    // Resolucao do erro Session is Closed ao comitar uma transacao pois se o ThreadTransaction
    // nao for nulo a threadTransaction pode ter sido obtida em uma sessao do hibernate diferente 
    // da atual e por este motivo a sessao pode estar fechada.

    Transaction tx = HibernateUtil.threadTransaction.get();
    //Transaction tx = HibernateUtil.getSessao().beginTransaction();

    if (tx == null) {
        tx = HibernateUtil.getSessao().beginTransaction();

        // bruno.lacerda@avantiprima.com.br
        String strTimeout = SigaBaseProperties.getString("jta.transaction.timeout.value");
        if (StringUtils.isNumeric(strTimeout)) {
            tx.setTimeout(Integer.parseInt(strTimeout));
        }/*from  w  ww.  j  ava 2s.  c o m*/

    }
    HibernateUtil.threadTransaction.set(tx);
}

From source file:com.byteslounge.spring.tx.MyOwnTxManager.java

License:Apache License

@Override
protected void doBegin(Object transaction, TransactionDefinition definition) {
    HibernateTransactionObject txObject = (HibernateTransactionObject) transaction;

    if (txObject.hasConnectionHolder() && !txObject.getConnectionHolder().isSynchronizedWithTransaction()) {
        throw new IllegalTransactionStateException(
                "Pre-bound JDBC Connection found! HibernateTransactionManager does not support "
                        + "running within DataSourceTransactionManager if told to manage the DataSource itself. "
                        + "It is recommended to use a single HibernateTransactionManager for all transactions "
                        + "on a single DataSource, no matter whether Hibernate or JDBC access.");
    }//from  w w  w.ja  v a 2 s  .c  o m

    Session session = null;

    try {
        if (txObject.getSessionHolder() == null
                || txObject.getSessionHolder().isSynchronizedWithTransaction()) {
            Session newSession = getSessionFactory().openSession();
            if (logger.isDebugEnabled()) {
                logger.debug("Opened new Session [" + newSession + "] for Hibernate transaction");
            }
            txObject.setSession(newSession);
        }

        session = txObject.getSessionHolder().getSession();

        if (this.prepareConnection && isSameConnectionForEntireSession(session)) {
            // We're allowed to change the transaction settings of the JDBC Connection.
            if (logger.isDebugEnabled()) {
                logger.debug("Preparing JDBC Connection of Hibernate Session [" + session + "]");
            }
            Connection con = ((SessionImplementor) session).connection();
            if (con.isClosed()) {
                System.out.println("Connection closed by exception");
            }
            Integer previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(con, definition);
            txObject.setPreviousIsolationLevel(previousIsolationLevel);
        } else {
            // Not allowed to change the transaction settings of the JDBC Connection.
            if (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT) {
                // We should set a specific isolation level but are not allowed to...
                throw new InvalidIsolationLevelException(
                        "HibernateTransactionManager is not allowed to support custom isolation levels: "
                                + "make sure that its 'prepareConnection' flag is on (the default) and that the "
                                + "Hibernate connection release mode is set to 'on_close' (SpringTransactionFactory's default).");
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Not preparing JDBC Connection of Hibernate Session [" + session + "]");
            }
        }

        if (definition.isReadOnly() && txObject.isNewSession()) {
            // Just set to NEVER in case of a new Session for this transaction.
            session.setFlushMode(FlushMode.MANUAL);
        }

        if (!definition.isReadOnly() && !txObject.isNewSession()) {
            // We need AUTO or COMMIT for a non-read-only transaction.
            FlushMode flushMode = session.getFlushMode();
            if (FlushMode.isManualFlushMode(session.getFlushMode())) {
                session.setFlushMode(FlushMode.AUTO);
                txObject.getSessionHolder().setPreviousFlushMode(flushMode);
            }
        }

        Transaction hibTx;

        // Register transaction timeout.
        int timeout = determineTimeout(definition);
        if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
            // Use Hibernate's own transaction timeout mechanism on Hibernate 3.1+
            // Applies to all statements, also to inserts, updates and deletes!
            hibTx = session.getTransaction();
            hibTx.setTimeout(timeout);
            hibTx.begin();
        } else {
            // Open a plain Hibernate transaction without specified timeout.
            hibTx = session.beginTransaction();
        }

        // Add the Hibernate transaction to the session holder.
        txObject.getSessionHolder().setTransaction(hibTx);

        // Register the Hibernate Session's JDBC Connection for the DataSource, if set.
        if (getDataSource() != null) {
            Connection con = ((SessionImplementor) session).connection();
            ConnectionHolder conHolder = new ConnectionHolder(con);
            if (timeout != TransactionDefinition.TIMEOUT_DEFAULT) {
                conHolder.setTimeoutInSeconds(timeout);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Exposing Hibernate transaction as JDBC transaction [" + con + "]");
            }
            TransactionSynchronizationManager.bindResource(getDataSource(), conHolder);
            txObject.setConnectionHolder(conHolder);
        }

        // Bind the session holder to the thread.
        if (txObject.isNewSessionHolder()) {
            TransactionSynchronizationManager.bindResource(getSessionFactory(), txObject.getSessionHolder());
        }
        txObject.getSessionHolder().setSynchronizedWithTransaction(true);
    }

    catch (Exception ex) {
        if (txObject.isNewSession()) {
            try {
                if (session.getTransaction().isActive()) {
                    session.getTransaction().rollback();
                }
            } catch (Throwable ex2) {
                logger.debug("Could not rollback Session after failed transaction begin", ex);
            } finally {
                SessionFactoryUtils.closeSession(session);
            }
        }
        throw new CannotCreateTransactionException("Could not open Hibernate Session for transaction", ex);
    }
}

From source file:com.consult.app.dao.impl.CargoMessageDaoImpl.java

public int save(CargoMessage obj) {
    Session session = null;/*from   ww w .  j a v a 2 s.com*/
    Transaction tx = null;
    try {
        CargoMessageInterceptor inter = new CargoMessageInterceptor(obj.getUpdateTime());
        session = sessionFactory.openSession(inter);
        tx = session.beginTransaction();
        tx.setTimeout(Constant.TRANSCTION_TIMEOUT);
        session.save(obj);
        tx.commit();
        return 1;
    } catch (Exception e) {
        e.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
        return 0;
    } finally {
        if (session != null) {
            session.close();
            session = null;
        }
    }
    //      sessionFactory.getCurrentSession().save(obj);
}

From source file:com.consult.app.dao.impl.CargoMessageDaoImpl.java

public void update(CargoMessage obj) {
    Session session = null;//from   ww w. ja  v a 2s.com
    Transaction tx = null;
    try {
        CargoMessageInterceptor inter = new CargoMessageInterceptor(obj.getUpdateTime());
        session = sessionFactory.openSession(inter);
        tx = session.beginTransaction();
        tx.setTimeout(Constant.TRANSCTION_TIMEOUT);
        session.update(obj);
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
            session = null;
        }
    }
    //      sessionFactory.getCurrentSession().update(obj);
}

From source file:com.consult.app.dao.impl.CargoMessageDaoImpl.java

public void delete(CargoMessage obj) {
    Session session = null;/*from   ww  w.  j  av  a2  s.  com*/
    Transaction tx = null;
    try {
        CargoMessageInterceptor inter = new CargoMessageInterceptor(obj.getUpdateTime());
        session = sessionFactory.openSession(inter);
        tx = session.beginTransaction();
        tx.setTimeout(Constant.TRANSCTION_TIMEOUT);
        session.delete(obj);
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
            session = null;
        }
    }
    //      sessionFactory.getCurrentSession().delete(obj);
}

From source file:com.consult.app.dao.impl.CargoMessageDaoImpl.java

@Override
public void updateMessage(IdTypeUpdateTimeRequest req, long userId) {
    String hql = "update CargoMessage message set message.type=-message.type, message.updateTime=? where message.userId=? and message.messageId=? and message.type<>? and message.type>=?";

    Session session = null;/*from w ww .  j  a  va2 s .c  o  m*/
    Transaction tx = null;
    try {
        CargoMessageInterceptor inter = new CargoMessageInterceptor(req.getUpdateTime());
        session = sessionFactory.openSession(inter);
        tx = session.beginTransaction();
        tx.setTimeout(Constant.TRANSCTION_TIMEOUT);
        Query query = session.createQuery(hql);
        //         query.setInteger(0, Constant.TYPE_DELETE);
        query.setLong(0, System.currentTimeMillis());
        query.setLong(1, userId);
        query.setLong(2, req.getId());
        query.setInteger(3, Constant.TYPE_ORDERED);
        query.setInteger(4, Constant.TYPE_NORMAL);
        query.executeUpdate();
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
            session = null;
        }
    }

}

From source file:com.consult.app.dao.impl.CargoMessageDaoImpl.java

@Override
public int refreshCargoMessages() {

    LogUtil.i(this.getClass().getSimpleName(), "refreshCargoMessages");
    Session session = null;/*from  w w  w . ja v a 2 s. c  o  m*/
    Transaction tx = null;
    int size = 0;
    long twenty_m_ago = System.currentTimeMillis() - 1200000;
    long now = System.currentTimeMillis();
    String hql = "update CargoMessage message set message.updateTime=?-(1200000-MOD(message.updateTime, 1200000)) where message.updateTime<=? and message.updateTime>? and message.type=1";
    try {
        CargoMessageInterceptor inter = new CargoMessageInterceptor(System.currentTimeMillis());
        session = sessionFactory.openSession(inter);
        tx = session.beginTransaction();
        tx.setTimeout(Constant.TRANSCTION_TIMEOUT);
        Query query = session.createQuery(hql);
        query.setLong(0, now);
        query.setLong(1, twenty_m_ago);
        query.setLong(2, TimeUtils.getStartOfDay(now));
        size = query.executeUpdate();
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
    } finally {
        if (session != null) {
            session.close();
            session = null;
        }
    }
    return size;
}

From source file:com.consult.app.dao.impl.CargoMessageDaoImpl.java

@Override
public int deleteClerkCargo(IdRequest req) {

    Session session = null;/*from   www  .  java2 s  .  com*/
    Transaction tx = null;
    long now = System.currentTimeMillis();
    String hql = "update CargoMessage message set message.type=-message.type where message.updateTime>? and message.type>0 and message.type<4 and message.messageId=?";
    try {
        CargoMessageInterceptor inter = new CargoMessageInterceptor(System.currentTimeMillis());
        session = sessionFactory.openSession(inter);
        tx = session.beginTransaction();
        tx.setTimeout(Constant.TRANSCTION_TIMEOUT);
        Query query = session.createQuery(hql);
        query.setLong(0, TimeUtils.getStartOfDay(now));
        query.setLong(1, req.getId());
        query.executeUpdate();
        tx.commit();
    } catch (Exception e) {
        e.printStackTrace();
        if (tx != null) {
            tx.rollback();
        }
        return Cookie.RESPONSE_SERVER_QUERY_ERROR;
    } finally {
        if (session != null) {
            session.close();
            session = null;
        }
    }
    return Cookie.RESPONSE_SUCCESS;
}

From source file:com.mycompany.thymeleafspringapp.dao.DealsDaoImpl.java

protected void persistDeal(Deals deal) throws HibernateException {
    Transaction tx = null;
    Session session = null;/*from w  w w  . j  av  a 2s  . c om*/
    try {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        tx.setTimeout(5);
        session.merge(deal);
        tx.commit();

    } catch (HibernateException e) {
        try {
            tx.rollback();
        } catch (RuntimeException rbe) {
            log.error("Couldnt roll back transaction", rbe);
        }
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:com.mycompany.thymeleafspringapp.dao.UsersDAOImpl.java

@Override
public Users createUser(String username, String password, String email) {
    Transaction tx = null;
    Session session = null;/*from w w  w  . j ava  2 s . c  om*/
    try {
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
        tx.setTimeout(5);
        Users user = new Users(0, username, password, email, Boolean.TRUE);
        session.persist(user);
        tx.commit();
        return user;

    } catch (RuntimeException e) {
        try {
            tx.rollback();
        } catch (RuntimeException rbe) {
            log.error("Couldnt roll back transaction", rbe);
        }
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }

}