Java Code Examples for org.hibernate.Session#getTransaction()

The following examples show how to use org.hibernate.Session#getTransaction() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/** {@inheritDoc} */
@Override public void onSessionEnd(CacheStoreSession ses, boolean commit) {
    Session hibSes = ses.attach(null);

    if (hibSes != null) {
        try {
            Transaction tx = hibSes.getTransaction();

            if (commit) {
                if (hibSes.isDirty())
                    hibSes.flush();

                if (tx.getStatus() == TransactionStatus.ACTIVE)
                    tx.commit();
            }
            else if (tx.getStatus().canRollback())
                tx.rollback();
        }
        catch (HibernateException e) {
            throw new CacheWriterException("Failed to end store session [tx=" + ses.transaction() + ']', e);
        }
        finally {
            hibSes.close();
        }
    }
}
 
Example 2
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
    super.afterTest();

    Session s = store.session(null);

    if (s == null)
        return;

    try {
        s.createQuery("delete from " + CacheHibernateBlobStoreEntry.class.getSimpleName())
                .setFlushMode(FlushMode.ALWAYS).executeUpdate();

        Transaction hTx = s.getTransaction();

        if (hTx != null && hTx.getStatus() == TransactionStatus.ACTIVE)
            hTx.commit();
    }
    finally {
        s.close();
    }
}
 
Example 3
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
    super.afterTest();

    Session s = store.session(null);

    if (s == null)
        return;

    try {
        s.createQuery("delete from " + CacheHibernateBlobStoreEntry.class.getSimpleName())
                .setFlushMode(FlushMode.ALWAYS).executeUpdate();

        Transaction hTx = s.getTransaction();

        if (hTx != null && hTx.getStatus() == TransactionStatus.ACTIVE)
            hTx.commit();
    }
    finally {
        s.close();
    }
}
 
Example 4
/** {@inheritDoc} */
@Override protected void afterTest() throws Exception {
    super.afterTest();

    Session s = store.session(null);

    if (s == null)
        return;

    try {
        s.createQuery("delete from " + CacheHibernateBlobStoreEntry.class.getSimpleName())
                .setFlushMode(FlushMode.ALWAYS).executeUpdate();

        Transaction hTx = s.getTransaction();

        if (hTx != null && hTx.isActive())
            hTx.commit();
    }
    finally {
        s.close();
    }
}
 
Example 5
public static void rollbackAndStartNewTransaction() {
	Session hibSession = HibernateUtil.getCurrentSession();
	Transaction existingTransaction = hibSession.getTransaction();
	try {
		existingTransaction.rollback();
	} catch (Exception ex) {
		org.webdsl.logging.Logger.error(ex);
		ex.printStackTrace();
		existingTransaction.rollback();
	} finally {
		Session newSession = ThreadLocalPage.get()
				.openNewTransactionThroughGetCurrentSession();
		newSession.setFlushMode(FlushMode.COMMIT);
		ThreadLocalPage.get().clearEntitiesToBeValidated();
		ThreadLocalPage.get().initVarsAndArgs();
	}
}
 
Example 6
Source Project: ignite   File: CacheHibernateBlobStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ends hibernate session.
 *
 * @param ses Hibernate session.
 * @param tx Cache ongoing transaction.
 */
private void end(Session ses, Transaction tx) {
    // Commit only if there is no cache transaction,
    // otherwise sessionEnd() will do all required work.
    if (tx == null) {
        org.hibernate.Transaction hTx = ses.getTransaction();

        if (hTx != null && hTx.getStatus() == TransactionStatus.ACTIVE)
            hTx.commit();

        ses.close();
    }
}
 
Example 7
Source Project: ignite   File: CacheHibernateBlobStore.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void sessionEnd(boolean commit) {
    init();

    Transaction tx = transaction();

    Map<String, Session> props = session().properties();

    Session ses = props.remove(ATTR_SES);

    if (ses != null) {
        org.hibernate.Transaction hTx = ses.getTransaction();

        if (hTx != null) {
            try {
                if (commit) {
                    ses.flush();

                    hTx.commit();
                }
                else
                    hTx.rollback();

                if (log.isDebugEnabled())
                    log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']');
            }
            catch (HibernateException e) {
                throw new CacheWriterException("Failed to end transaction [xid=" + tx.xid() +
                    ", commit=" + commit + ']', e);
            }
            finally {
                ses.close();
            }
        }
    }
}
 
Example 8
Source Project: ignite   File: CacheHibernateBlobStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ends hibernate session.
 *
 * @param ses Hibernate session.
 * @param tx Cache ongoing transaction.
 */
private void end(Session ses, Transaction tx) {
    // Commit only if there is no cache transaction,
    // otherwise sessionEnd() will do all required work.
    if (tx == null) {
        org.hibernate.Transaction hTx = ses.getTransaction();

        if (hTx != null && hTx.getStatus() == TransactionStatus.ACTIVE)
            hTx.commit();

        ses.close();
    }
}
 
Example 9
Source Project: ignite   File: CacheHibernateBlobStore.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void sessionEnd(boolean commit) {
    init();

    Transaction tx = transaction();

    Map<String, Session> props = session().properties();

    Session ses = props.remove(ATTR_SES);

    if (ses != null) {
        org.hibernate.Transaction hTx = ses.getTransaction();

        if (hTx != null) {
            try {
                if (commit) {
                    ses.flush();

                    hTx.commit();
                }
                else
                    hTx.rollback();

                if (log.isDebugEnabled())
                    log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']');
            }
            catch (HibernateException e) {
                throw new CacheWriterException("Failed to end transaction [xid=" + tx.xid() +
                    ", commit=" + commit + ']', e);
            }
            finally {
                ses.close();
            }
        }
    }
}
 
Example 10
Source Project: ignite   File: CacheHibernateBlobStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Ends hibernate session.
 *
 * @param ses Hibernate session.
 * @param tx Cache ongoing transaction.
 */
private void end(Session ses, Transaction tx) {
    // Commit only if there is no cache transaction,
    // otherwise sessionEnd() will do all required work.
    if (tx == null) {
        org.hibernate.Transaction hTx = ses.getTransaction();

        if (hTx != null && hTx.isActive())
            hTx.commit();

        ses.close();
    }
}
 
Example 11
Source Project: ignite   File: CacheHibernateBlobStore.java    License: Apache License 2.0 5 votes vote down vote up
/** {@inheritDoc} */
@Override public void sessionEnd(boolean commit) {
    init();

    Transaction tx = transaction();

    Map<String, Session> props = session().properties();

    Session ses = props.remove(ATTR_SES);

    if (ses != null) {
        org.hibernate.Transaction hTx = ses.getTransaction();

        if (hTx != null) {
            try {
                if (commit) {
                    ses.flush();

                    hTx.commit();
                }
                else
                    hTx.rollback();

                if (log.isDebugEnabled())
                    log.debug("Transaction ended [xid=" + tx.xid() + ", commit=" + commit + ']');
            }
            catch (HibernateException e) {
                throw new CacheWriterException("Failed to end transaction [xid=" + tx.xid() +
                    ", commit=" + commit + ']', e);
            }
            finally {
                ses.close();
            }
        }
    }
}
 
Example 12
Source Project: unitime   File: _BaseRootDAO.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Begin the transaction related to the session
 */
public Transaction beginTransaction(Session s) {
	// already in a transaction, do not create a new one
	if (s.getTransaction() != null && s.getTransaction().isActive()) return null;
	
	return s.beginTransaction();
}
 
Example 13
Source Project: tutorials   File: FooFixtures.java    License: MIT License 5 votes vote down vote up
public void createBars() {
    Session session = null;
    Transaction tx = null;
    session = sessionFactory.openSession();
    tx = session.getTransaction();
    try {
        tx.begin();
        for (int i = 156; i < 160; i++) {
            final Bar bar = new Bar();
            bar.setName("Bar_" + i);
            final Foo foo = new Foo("Foo_" + (i + 120));
            foo.setBar(bar);
            session.save(foo);
            final Foo foo2 = new Foo(null);
            if (i % 2 == 0)
                foo2.setName("LuckyFoo" + (i + 120));
            foo2.setBar(bar);
            session.save(foo2);
            bar.getFooSet().add(foo);
            bar.getFooSet().add(foo2);
            session.merge(bar);
        }
        tx.commit();
        session.flush();
    } catch (final HibernateException he) {
        if (tx != null)
            tx.rollback();
        System.out.println("Not able to open session");
        he.printStackTrace();
    } catch (final Exception e) {
        e.printStackTrace();
    } finally {
        if (session != null)
            session.close();
    }

}
 
Example 14
/**
 */
private void checkSession() {
    Session hibSes = ses.attachment();

    assertNotNull(hibSes);

    assertTrue(hibSes.isOpen());

    Transaction tx = hibSes.getTransaction();

    assertNotNull(tx);

    if (ses.isWithinTransaction())
        assertEquals(TransactionStatus.ACTIVE, tx.getStatus());
    else
        assertFalse("Unexpected status: " + tx.getStatus(), tx.getStatus() == TransactionStatus.ACTIVE);

    verifySameInstance(hibSes);
}
 
Example 15
Source Project: commafeed   File: UnitOfWork.java    License: Apache License 2.0 4 votes vote down vote up
private static void commitTransaction(Session session) {
	final Transaction txn = session.getTransaction();
	if (txn != null && txn.isActive()) {
		txn.commit();
	}
}
 
Example 16
/**
 */
private void checkSession() {
    Session hibSes = ses.attachment();

    assertNotNull(hibSes);

    assertTrue(hibSes.isOpen());

    Transaction tx = hibSes.getTransaction();

    assertNotNull(tx);

    if (ses.isWithinTransaction())
        assertEquals(TransactionStatus.ACTIVE, tx.getStatus());
    else
        assertFalse("Unexpected status: " + tx.getStatus(), tx.getStatus() == TransactionStatus.ACTIVE);

    verifySameInstance(hibSes);
}
 
Example 17
Source Project: tutorials   File: HibernateLifecycleUtil.java    License: MIT License 4 votes vote down vote up
public static Transaction startTransaction(Session s) {
    Transaction tx = s.getTransaction();
    tx.begin();
    return tx;
}
 
Example 18
Source Project: commafeed   File: UnitOfWork.java    License: Apache License 2.0 4 votes vote down vote up
private static void rollbackTransaction(Session session) {
	final Transaction txn = session.getTransaction();
	if (txn != null && txn.isActive()) {
		txn.rollback();
	}
}
 
Example 19
Source Project: unitime   File: Exam.java    License: Apache License 2.0 4 votes vote down vote up
public String unassign(String managerExternalId, Session hibSession) {
    Transaction tx = null;
    try {
        if (hibSession.getTransaction()==null || !hibSession.getTransaction().isActive())
            tx = hibSession.beginTransaction();
        
        ExamAssignment oldAssignment = new ExamAssignment(this);
        
        setAssignedPeriod(null);
        if (getAssignedRooms()==null) setAssignedRooms(new HashSet());
        getAssignedRooms().clear();
        setAssignedPreference(null);
        
        HashSet otherExams = new HashSet();
        
        for (Iterator j=getConflicts().iterator();j.hasNext();) {
            ExamConflict conf = (ExamConflict)j.next();
            for (Iterator i=conf.getExams().iterator();i.hasNext();) {
                Exam x = (Exam)i.next();
                if (!x.equals(this)) {
                    x.getConflicts().remove(conf);
                    otherExams.add(x);
                }
            }
            hibSession.delete(conf);
            j.remove();
        }

        ExamEvent event = getEvent();
        if (event!=null) hibSession.delete(event);
        
        hibSession.update(this);
        for (Iterator i=otherExams.iterator();i.hasNext();)
            hibSession.update((Exam)i.next());
        
        SubjectArea subject = null;
        Department dept = null;
        for (Iterator i=new TreeSet(getOwners()).iterator();i.hasNext();) {
            ExamOwner owner = (ExamOwner)i.next();
            subject = owner.getCourse().getSubjectArea();
            dept = subject.getDepartment();
            break;
        }
        
        ChangeLog.addChange(hibSession,
                TimetableManager.findByExternalId(managerExternalId),
                getSession(),
                this,
                getName()+" ("+
                (oldAssignment.getPeriod()==null?"N/A":oldAssignment.getPeriodAbbreviation()+" "+oldAssignment.getRoomsName(", "))+
                " &rarr; N/A)",
                ChangeLog.Source.EXAM_INFO,
                ChangeLog.Operation.UNASSIGN,
                subject,
                dept);

        if (tx!=null) tx.commit();
        return null;
    } catch (Exception e) {
        if (tx!=null) tx.rollback();
        e.printStackTrace();
        return "Unassignment of "+getName()+" failed, reason: "+e.getMessage();
    }
}
 
Example 20
Source Project: coditori   File: Application.java    License: Apache License 2.0 3 votes vote down vote up
public static void main(String[] args) {

        Session s = HibernateConfig.getSession();
        Transaction tx= s.getTransaction();

        User user = new User();
        user.setName("Masoud");

        tx.begin();

        s.save(user);

        tx.commit();
        s.close();
    }