Java Code Examples for org.hibernate.context.internal.ManagedSessionContext#bind()

The following examples show how to use org.hibernate.context.internal.ManagedSessionContext#bind() . 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
Source File: UnitOfWork.java    From commafeed with Apache License 2.0 6 votes vote down vote up
public static <T> T call(SessionFactory sessionFactory, SessionRunnerReturningValue<T> sessionRunner) {
	final Session session = sessionFactory.openSession();
	if (ManagedSessionContext.hasBind(sessionFactory)) {
		throw new IllegalStateException("Already in a unit of work!");
	}
	T t = null;
	try {
		ManagedSessionContext.bind(session);
		session.beginTransaction();
		try {
			t = sessionRunner.runInSession();
			commitTransaction(session);
		} catch (Exception e) {
			rollbackTransaction(session);
			UnitOfWork.<RuntimeException> rethrow(e);
		}
	} finally {
		session.close();
		ManagedSessionContext.unbind(sessionFactory);
	}
	return t;
}
 
Example 2
Source File: DbClearRule.java    From flux with Apache License 2.0 6 votes vote down vote up
/**
 * Clears all given tables which are mentioned using the given sessionFactory
 */
private void clearDb(Class[] tables, SessionFactory sessionFactory) {
    Session session = sessionFactory.openSession();
    ManagedSessionContext.bind(session);
    Transaction tx = session.beginTransaction();
    try {
            session.createSQLQuery("set foreign_key_checks=0").executeUpdate();
        for (Class anEntity : tables) {
            session.createSQLQuery("delete from " + anEntity.getSimpleName() + "s").executeUpdate(); //table name is plural form of class name, so appending 's'
        }
            session.createSQLQuery("set foreign_key_checks=1").executeUpdate();
        tx.commit();
    } catch (Exception e) {
        if (tx != null)
            tx.rollback();
        throw new RuntimeException("Unable to clear tables. Exception: " + e.getMessage(), e);
    } finally {
        if (session != null) {
            ManagedSessionContext.unbind(sessionFactory);
            session.close();
        }
    }
}
 
Example 3
Source File: EventSchedulerDaoTest.java    From flux with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    Session session = sessionFactory.getSchedulerSessionFactory().openSession();
    ManagedSessionContext.bind(session);
    Transaction tx = session.beginTransaction();
    try {
        session.createSQLQuery("delete from ScheduledEvents").executeUpdate();
        tx.commit();
    } finally {
        if (session != null) {
            ManagedSessionContext.unbind(session.getSessionFactory());
            session.close();
            sessionFactory.clear();
        }
    }
}
 
Example 4
Source File: MessageDaoTest.java    From flux with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    context.setThreadLocalSession(context.getSchedulerSessionFactory().openSession());
    Session session = context.getThreadLocalSession();
    ManagedSessionContext.bind(session);
    Transaction tx = session.beginTransaction();
    try {
        session.createSQLQuery("delete from ScheduledMessages").executeUpdate();
        tx.commit();
    } finally {
        if(session != null) {
            ManagedSessionContext.unbind(context.getThreadLocalSession().getSessionFactory());
            session.close();
            context.clear();
        }
    }
}
 
Example 5
Source File: AuthenticatedWebSocket.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public String onConnect(Session session) {
    for (HttpCookie cookie : session.getUpgradeRequest().getCookies()) {
        if ("auth-token".equals(cookie.getName())) {
            String authToken = cookie.getValue();
            TokenAuthenticator authenticator = getAuthenticator();
            org.hibernate.Session hSession = sessionFactory.openSession();
            ManagedSessionContext.bind(hSession);
            Optional<BasicToken> token;
            try {
                token = authenticator.authenticate(authToken);
            } catch (AuthenticationException e) {
                e.printStackTrace();
                return null;
            }
            if (!token.isPresent()) {
                return null;
            }
            hSession.close();
            return token.get().getUserId();
        }
    }
    return null;
}
 
Example 6
Source File: SystemParameterCacheTest.java    From robe with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
public void get() {

    SessionFactory sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
    ManagedSessionContext.bind(sessionFactory.openSession());
    SystemParameterDao dao = new SystemParameterDao(sessionFactory);

    SystemParameter parameter = new SystemParameter();
    parameter.setValue("ROBE");
    parameter.setKey("TEST");
    parameter = dao.create(parameter);
    dao.flush();

    Object value = SystemParameterCache.get("DEFAULT", "default"); // TODO GuiceBundle not initialized
    Assert.assertTrue(value.equals("default"));

    Object value2 = SystemParameterCache.get("TEST", "none");
    Assert.assertTrue(value2.equals("ROBE"));

    dao.detach(parameter);
    dao.delete(parameter);
    dao.flush();
}
 
Example 7
Source File: JobPersister.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
public JobPersister(ConcurrentHashMap<String, JobInfo> jobs) {
    SessionFactory sessionFactory = GuiceBundle.getInjector().getInstance(SessionFactory.class);
    ManagedSessionContext.bind(sessionFactory.openSession());
    JobDao jobDao = new JobDao(sessionFactory);
    TriggerDao triggerDao = new TriggerDao(sessionFactory);
    for (JobInfo info : jobs.values()) {
        insertOrUpdate(jobDao, info, triggerDao);
    }
    sessionFactory.getCurrentSession().flush();
    sessionFactory.getCurrentSession().close();
    ManagedSessionContext.unbind(sessionFactory);
}
 
Example 8
Source File: UnitOfWorkInvoker.java    From dropwizard-jaxws with Apache License 2.0 5 votes vote down vote up
@Override
public Object invoke(Exchange exchange, Object o) {

    Object result;
    String methodname = this.getTargetMethod(exchange).getName();

    if (unitOfWorkMethods.containsKey(methodname)) {

        final Session session = sessionFactory.openSession();
        UnitOfWork unitOfWork = unitOfWorkMethods.get(methodname);

        try {
            configureSession(session, unitOfWork);
            ManagedSessionContext.bind(session);
            beginTransaction(session, unitOfWork);
            try {
                result = underlying.invoke(exchange, o);
                commitTransaction(session, unitOfWork);
                return result;
            } catch (Exception e) {
                rollbackTransaction(session, unitOfWork);
                this.<RuntimeException>rethrow(e); // unchecked rethrow
                return null; // avoid compiler warning
            }
        } finally {
            session.close();
            ManagedSessionContext.unbind(sessionFactory);
        }
    }
    else {
        return underlying.invoke(exchange, o);
    }
}
 
Example 9
Source File: Transaction.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Closes and unbinds the current session. <br/>
 * If {@link ManagedSessionContext} had a session before the current session, re-binds it to {@link ManagedSessionContext}
 */
private void finish() {
    try {
        if (session != null) {
            session.close();
        }
    } finally {
        ManagedSessionContext.unbind(SESSION_FACTORY);
        if (!SESSIONS.get().isEmpty()) {
            ManagedSessionContext.bind(SESSIONS.get().pop());
        }
    }
}
 
Example 10
Source File: BaseDaoTest.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Before
public void before() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    if (sessionFactory == null) {
        sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
        ManagedSessionContext.bind(sessionFactory.openSession());
        this.daoClazz = (Class<D>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1];
        dao = daoClazz.getDeclaredConstructor(SessionFactory.class).newInstance(sessionFactory);
    }
}
 
Example 11
Source File: RoleResourceTest.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void getRolePermissions() throws IOException {
    SessionFactory sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
    ManagedSessionContext.bind(sessionFactory.openSession());
    RoleDao roleDao = new RoleDao(sessionFactory);
    Role role = roleDao.findByCode("all");
    Assert.assertTrue(role != null);
    TestRequest request = getRequestBuilder().endpoint(role.getId() + "/permissions").build();
    TestResponse response = client.get(request);
    Map result = response.get(Map.class);

    Assert.assertTrue(result.get("menu") != null);
    Assert.assertTrue(result.get("service") != null);
    ManagedSessionContext.unbind(sessionFactory);
}
 
Example 12
Source File: SystemParameterCache.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static void fillCache() {

        SessionFactory sessionFactory = RobeHibernateBundle.getInstance().getSessionFactory();
        ManagedSessionContext.bind(sessionFactory.openSession());
        SystemParameterDao dao = new SystemParameterDao(sessionFactory);

        List<SystemParameter> parameters = dao.findAllStrict();

        for (SystemParameter parameter : parameters) {
            cache.put(parameter.getKey(), parameter.getValue());
            dao.detach(parameter);// TODO
        }

    }
 
Example 13
Source File: HibernateSessionExtension.java    From judgels with GNU General Public License v2.0 5 votes vote down vote up
private void openSession(SessionFactory sessionFactory, ExtensionContext context) {
    Session session = sessionFactory.openSession();
    Transaction txn = session.beginTransaction();
    ManagedSessionContext.bind(session);

    SessionContext sessionContext = new SessionContext(sessionFactory, session, txn);
    getStore(context).put(context.getUniqueId(), sessionContext);
}
 
Example 14
Source File: ClientElbDAOTest.java    From flux with Apache License 2.0 5 votes vote down vote up
private void clean() throws Exception {
    Session session = sessionFactory.getSchedulerSessionFactory().openSession();
    ManagedSessionContext.bind(session);
    Transaction tx = session.beginTransaction();
    try {
        session.createSQLQuery("delete from ClientElb").executeUpdate();
        tx.commit();
    } finally {
        if (session != null) {
            ManagedSessionContext.unbind(session.getSessionFactory());
            session.close();
            sessionFactory.clear();
        }
    }
}
 
Example 15
Source File: ClientElbPersistenceServiceTest.java    From flux with Apache License 2.0 5 votes vote down vote up
private void clean() throws Exception {
    Session session = sessionFactory.getSchedulerSessionFactory().openSession();
    ManagedSessionContext.bind(session);
    Transaction tx = session.beginTransaction();
    try {
        session.createSQLQuery("delete from ClientElb").executeUpdate();
        tx.commit();
    } finally {
        if (session != null) {
            ManagedSessionContext.unbind(session.getSessionFactory());
            session.close();
            sessionFactory.clear();
        }
    }
}
 
Example 16
Source File: TransactionAwareSessionContext.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Binds the configured session to Spring's transaction manager strategy if there's no session.
    *
    * @return Returns the configured session, or the one managed by Spring. Never returns null.
    */
   @Override
   public Session currentSession() {
try {
    Session s = defaultSessionContext.currentSession();
    return s;
} catch (HibernateException cause) {

    // There's no session bound to the current thread. Let's open one if
    // needed.
    if (ManagedSessionContext.hasBind(sessionFactory)) {
	return localSessionContext.currentSession();
    }

    Session session;
    session = sessionFactory.openSession();
    TransactionAwareSessionContext.logger.warn("No Session bound to current Thread. Opened new Session ["
	    + session + "]. Transaction: " + session.getTransaction());

    if (registerSynchronization(session)) {
	// Normalizes Session flush mode, defaulting it to AUTO. Required for
	// synchronization. LDEV-4696 Updated for Hibernate 5.3. See SPR-14364.
	FlushMode flushMode = session.getHibernateFlushMode();

	if (FlushMode.MANUAL.equals(flushMode)
		&& !TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
	    session.setFlushMode(FlushMode.AUTO);
	}
    }
    ManagedSessionContext.bind(session);

    return session;
}
   }
 
Example 17
Source File: Transaction.java    From robe with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * Opens a new session, sets flush mode and bind this session to {@link ManagedSessionContext}
 */
private void configureNewSession() {
    session = SESSION_FACTORY.openSession();
    session.setFlushMode(flushMode);
    ManagedSessionContext.bind(session);
}