Example usage for org.hibernate SessionFactory getCurrentSession

List of usage examples for org.hibernate SessionFactory getCurrentSession

Introduction

In this page you can find the example usage for org.hibernate SessionFactory getCurrentSession.

Prototype

Session getCurrentSession() throws HibernateException;

Source Link

Document

Obtains the current session.

Usage

From source file:org.owasp.dependencytrack.util.session.RunWithSession.java

License:Open Source License

public static void run(SessionFactory sessionFactory, DBSessionTask runnable) {
    Session session = null;/*from   w w w  .  j av  a2s  .co  m*/
    try {
        session = sessionFactory.getCurrentSession();
    } catch (Throwable t) {

    }

    boolean manageSession = (session == null) || !session.isOpen();
    if (manageSession) {
        session = sessionFactory.openSession();
    }
    if (session != null) {
        try {
            runnable.run(session);
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            if (session != null && session.isOpen()) {
                session.flush();
                if (manageSession) {
                    session.close();
                }

            }
        }
    }

}

From source file:org.riotfamily.common.hibernate.HibernateUtils.java

License:Apache License

public static Serializable getIdAndSaveIfNecessary(SessionFactory sessionFactory, Object bean) {
    Serializable id = getId(sessionFactory, bean);
    if (id == null) {
        sessionFactory.getCurrentSession().save(bean);
    }/*from   w  w w.j  av a2 s.c o m*/
    return getId(sessionFactory, bean);
}

From source file:org.snaker.engine.access.hibernate.HibernateHelper.java

License:Apache License

public static Session getSession(SessionFactory sf) {
    Session session = (Session) TransactionObjectHolder.get();
    if (session == null) {
        /*/*from  ww  w . ja va 2  s.  c  o m*/
         * ioc???sessionFactory??session
         * ?openSession???
         */
        if (sf != null)
            return sf.getCurrentSession();
        if (log.isDebugEnabled()) {
            log.debug("could not found sessionFactory.");
        }
        return getSessionFactory().openSession();
    } else {
        if (log.isDebugEnabled()) {
            log.debug("found thread-bound session=" + session.hashCode());
        }
        return session;
    }
}

From source file:org.springframework.batch.item.database.Hibernate5ItemWriter.java

License:Apache License

/**
 * Do perform the actual write operation using Hibernate's API.
 * This can be overridden in a subclass if necessary.
 *
 * @param sessionFactory Hibernate SessionFactory to be used
 * @param items the list of items to use for the write
 *//*w ww.j a  va  2s . c  om*/
protected void doWrite(SessionFactory sessionFactory, List<? extends T> items) {
    if (logger.isDebugEnabled()) {
        logger.debug("Writing to Hibernate with " + items.size() + " items.");
    }

    Session currentSession = sessionFactory.getCurrentSession();

    if (!items.isEmpty()) {
        long saveOrUpdateCount = 0;
        for (T item : items) {
            if (!currentSession.contains(item)) {
                currentSession.saveOrUpdate(item);
                saveOrUpdateCount++;
            }
        }
        if (logger.isDebugEnabled()) {
            logger.debug(saveOrUpdateCount + " entities saved/updated.");
            logger.debug((items.size() - saveOrUpdateCount) + " entities found in session.");
        }
    }
}

From source file:org.springframework.orm.hibernate3.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionRollbackWithHibernateManagedSession() throws Exception {
    final SessionFactory sf = mock(SessionFactory.class);
    final Session session = mock(Session.class);
    final Transaction tx1 = mock(Transaction.class);
    final Transaction tx2 = mock(Transaction.class);

    given(sf.getCurrentSession()).willReturn(session);
    given(session.isOpen()).willReturn(true);
    given(session.getTransaction()).willReturn(tx1, tx2);
    given(session.beginTransaction()).willReturn(tx1, tx2);
    given(session.getFlushMode()).willReturn(FlushMode.MANUAL);

    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf);/* w  w w .j a  va  2 s. c  o m*/
    tm.setPrepareConnection(false);
    tm.setHibernateManagedSession(true);
    final TransactionTemplate tt = new TransactionTemplate(tm);

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));

    try {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
                tt.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    public void doInTransactionWithoutResult(TransactionStatus status) {
                        status.setRollbackOnly();
                        HibernateTemplate ht = new HibernateTemplate(sf);
                        ht.setAllowCreate(false);
                        ht.setExposeNativeSession(true);
                        ht.execute(new HibernateCallback() {
                            @Override
                            public Object doInHibernate(org.hibernate.Session sess) throws HibernateException {
                                assertEquals(session, sess);
                                return null;
                            }
                        });
                    }
                });
            }
        });
        fail("Should have thrown UnexpectedRollbackException");
    } catch (UnexpectedRollbackException ex) {
        // expected
    }

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));

    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            HibernateTemplate ht = new HibernateTemplate(sf);
            ht.setAllowCreate(false);
            ht.setExposeNativeSession(true);
            ht.execute(new HibernateCallback() {
                @Override
                public Object doInHibernate(org.hibernate.Session sess) throws HibernateException {
                    assertEquals(session, sess);
                    return null;
                }
            });
        }
    });

    verify(tx1).rollback();
    verify(tx2).commit();
    InOrder ordered = inOrder(session);
    ordered.verify(session).setFlushMode(FlushMode.AUTO);
    ordered.verify(session).setFlushMode(FlushMode.MANUAL);
}

From source file:org.springframework.orm.hibernate4.HibernateTransactionManagerTests.java

License:Apache License

@Test
public void testTransactionRollbackWithHibernateManagedSession() throws Exception {
    final SessionFactory sf = mock(SessionFactory.class);
    final Session session = mock(Session.class);
    final Transaction tx1 = mock(Transaction.class);
    final Transaction tx2 = mock(Transaction.class);

    given(sf.getCurrentSession()).willReturn(session);
    given(session.isOpen()).willReturn(true);
    given(session.getTransaction()).willReturn(tx1, tx2);
    given(session.beginTransaction()).willReturn(tx1, tx2);
    given(session.getFlushMode()).willReturn(FlushMode.MANUAL);

    HibernateTransactionManager tm = new HibernateTransactionManager();
    tm.setSessionFactory(sf);/*  w ww  . ja  v  a  2  s  .  co m*/
    tm.setPrepareConnection(false);
    tm.setHibernateManagedSession(true);
    final TransactionTemplate tt = new TransactionTemplate(tm);

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));

    try {
        tt.execute(new TransactionCallbackWithoutResult() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
                tt.execute(new TransactionCallbackWithoutResult() {
                    @Override
                    public void doInTransactionWithoutResult(TransactionStatus status) {
                        status.setRollbackOnly();
                        Session sess = ((SessionHolder) TransactionSynchronizationManager.getResource(sf))
                                .getSession();
                        assertEquals(session, sess);
                    }
                });
            }
        });
        fail("Should have thrown UnexpectedRollbackException");
    } catch (UnexpectedRollbackException ex) {
        // expected
    }

    assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));

    tt.execute(new TransactionCallbackWithoutResult() {
        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) {
            assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
            Session sess = ((SessionHolder) TransactionSynchronizationManager.getResource(sf)).getSession();
            assertEquals(session, sess);
        }
    });

    verify(tx1).rollback();
    verify(tx2).commit();
    InOrder ordered = inOrder(session);
    ordered.verify(session).setFlushMode(FlushMode.AUTO);
    ordered.verify(session).setFlushMode(FlushMode.MANUAL);
}

From source file:org.usip.osp.persistence.MultiSchemaHibernateUtil.java

License:Open Source License

/**
 * Returns the session for the schema. /*from   w  w  w . j  ava  2  s. c  o m*/
 * @param schema
 * @param root
 * @return
 */
public static Session getSession(String schema, boolean root) {

    SessionFactory factory = (SessionFactory) setOfSessionFactories.get(schema);

    if (factory == null) {
        Logger.getRootLogger().warn("starting with schema : " + schema); //$NON-NLS-1$
        Configuration config = MultiSchemaHibernateUtil.getInitializedConfiguration(schema, root);
        factory = config.buildSessionFactory();
        setOfSessionFactories.put(schema, factory);
    }

    Session s = null;

    try {

        s = factory.getCurrentSession();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return s;

}

From source file:org.vpac.grisu.hibernate.HibernateHelpers.java

License:Open Source License

public static String getUniqueName(String jobname, String dn) {

    String name = jobname;//  w w  w .  j  a  v  a 2 s .  c  o m

    SessionFactory sf = HibernateSessionFactory.getSessionFactory();

    Session session = sf.getCurrentSession();

    Query q = session.createQuery(
            "select job.jobname from org.vpac.grisu.js.model.job.Job as job where job.dn=? and job.jobname like ?");
    q.setString(0, dn);
    q.setString(1, jobname + "%");

    List jobs = q.list();
    int i = 0;
    boolean taken = false;
    do {
        taken = false;
        if (i != 0)
            name = jobname + "_" + (jobs.size() + i);
        for (Object job : jobs) {
            if (((String) job).equals(name)) {
                taken = true;
                break;
            }
        }
        i++;
    } while (taken);
    return name;
}

From source file:org.wso2.appserver.hibernate.jndi.sample.listener.EmployeeManager.java

License:Open Source License

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    SessionFactory sessionFactory = (SessionFactory) request.getServletContext().getAttribute("SessionFactory");
    Session session = sessionFactory.getCurrentSession();

    Transaction tx = session.beginTransaction();
    String empName = request.getParameter("empName");
    Employee employee = new Employee();
    employee.setName(empName);// ww w  .j av  a2s. c o  m
    session.persist(employee);
    tx.commit();

    PrintWriter out = response.getWriter();
    out.print("Successfully persist the Employee");
}

From source file:org.wso2.mercury.persistence.hibernate.HibernatePersistenceManagerTest.java

License:Apache License

public void testDisplayDataBase() {
    // dispay internal key table
    SessionFactory sessionFactory = getConfiguration().buildSessionFactory();
    Session session = sessionFactory.getCurrentSession();
    session.beginTransaction();//from www  .  j  a v  a  2 s  .c  o  m
    List internalKeys = session.createQuery("from InternalKeyDto").list();
    List rmsSequences = session.createQuery("from RMSSequenceDto").list();
    List rmsMessages = session.createQuery("from RMSMessageDto").list();
    List rmdSequences = session.createQuery("from RMDSequenceDto").list();
    List invokerBuffers = session.createQuery("from InvokerBufferDto").list();
    List rmdMessages = session.createQuery("from RMDMessageDto").list();
    List sequenceReceivedNumbers = session.createQuery("from SequenceReceivedNumberDto").list();
    List bufferReceivedNumbers = session.createQuery("from BufferReceivedNumberDto").list();
    List axis2Infos = session.createQuery("from Axis2InfoDto").list();
    List engagedModules = session.createQuery("from EngagedModuleDto").list();
    List properties = session.createQuery("from PropertyDto").list();

    displayInternalKeys(internalKeys);
    displayRMSSequences(rmsSequences);
    displayRMSMessages(rmsMessages);
    displayRMDSequences(rmdSequences);
    displayInvokerBuffers(invokerBuffers);
    displayRMDMessages(rmdMessages);
    displaySequenceReceivedNumbers(sequenceReceivedNumbers);
    displayBufferReceivedNumbers(bufferReceivedNumbers);
    displayAxisInfo(axis2Infos);
    displayEngagedModule(engagedModules);
    displayProperty(properties);
    session.getTransaction().commit();
}