Java Code Examples for org.hibernate.FlushMode

The following examples show how to use org.hibernate.FlushMode. 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
Source Project: quarkus   Source File: JpaIdentityProvider.java    License: Apache License 2.0 7 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(UsernamePasswordAuthenticationRequest request,
        AuthenticationRequestContext context) {
    return context.runBlocking(new Supplier<SecurityIdentity>() {
        @Override
        public SecurityIdentity get() {
            // FIXME: unit name
            EntityManager em = jpaConfig.getEntityManagerFactory(null).createEntityManager();
            ((org.hibernate.Session) em).setHibernateFlushMode(FlushMode.MANUAL);
            ((org.hibernate.Session) em).setDefaultReadOnly(true);
            try {
                return authenticate(em, request);
            } catch (SecurityException e) {
                log.debug("Authentication failed", e);
                throw new AuthenticationFailedException();
            } finally {
                em.close();
            }
        }
    });
}
 
Example 2
Source Project: ignite   Source File: CacheHibernateBlobStoreSelfTest.java    License: Apache License 2.0 6 votes vote down vote up
/** {@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 3
Source Project: lams   Source File: FlushModeConverter.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static FlushMode fromXml(String name) {
	// valid values are a subset of all FlushMode possibilities, so we will
	// handle the conversion here directly.
	// Also, we want to map "never"->MANUAL (rather than NEVER)
	if ( name == null ) {
		return null;
	}

	if ( "never".equalsIgnoreCase( name ) ) {
		return FlushMode.MANUAL;
	}
	else if ( "auto".equalsIgnoreCase( name ) ) {
		return FlushMode.AUTO;
	}
	else if ( "always".equalsIgnoreCase( name ) ) {
		return FlushMode.ALWAYS;
	}

	// if the incoming value was not null *and* was not one of the pre-defined
	// values, we need to throw an exception.  This *should never happen if the
	// document we are processing conforms to the schema...
	throw new HibernateException( "Unrecognized flush mode : " + name );
}
 
Example 4
Source Project: lams   Source File: SessionFactoryImpl.java    License: GNU General Public License v2.0 6 votes vote down vote up
SessionBuilderImpl(SessionFactoryImpl sessionFactory) {
	this.sessionFactory = sessionFactory;
	this.sessionOwner = null;

	// set up default builder values...
	this.statementInspector = sessionFactory.getSessionFactoryOptions().getStatementInspector();
	this.connectionHandlingMode = sessionFactory.getSessionFactoryOptions().getPhysicalConnectionHandlingMode();
	this.autoClose = sessionFactory.getSessionFactoryOptions().isAutoCloseSessionEnabled();
	this.flushMode = sessionFactory.getSessionFactoryOptions().isFlushBeforeCompletionEnabled()
			? FlushMode.AUTO
			: FlushMode.MANUAL;

	if ( sessionFactory.getCurrentTenantIdentifierResolver() != null ) {
		tenantIdentifier = sessionFactory.getCurrentTenantIdentifierResolver().resolveCurrentTenantIdentifier();
	}
	this.jdbcTimeZone = sessionFactory.getSessionFactoryOptions().getJdbcTimeZone();

	listeners = sessionFactory.getSessionFactoryOptions().getBaselineSessionEventsListenerBuilder().buildBaselineList();
	queryParametersValidationEnabled = sessionFactory.getSessionFactoryOptions().isQueryParametersValidationEnabled();
}
 
Example 5
@Override
public Mutiny.Session setFlushMode(FlushMode flushMode) {
	switch (flushMode) {
		case COMMIT:
			delegate.setHibernateFlushMode(FlushMode.COMMIT);
			break;
		case AUTO:
			delegate.setHibernateFlushMode(FlushMode.AUTO);
			break;
		case MANUAL:
			delegate.setHibernateFlushMode(FlushMode.MANUAL);
			break;
		case ALWAYS:
			delegate.setHibernateFlushMode(FlushMode.ALWAYS);
			break;
	}
	return this;
}
 
Example 6
@Override
public void onPostInsert(PostInsertEvent event) throws HibernateException {
    final Object entity = event.getEntity();

    if(entity instanceof Post) {
        Post post = (Post) entity;

        event.getSession().createNativeQuery(
            "INSERT INTO old_post (id, title, version) " +
            "VALUES (:id, :title, :version)")
        .setParameter("id", post.getId())
        .setParameter("title", post.getTitle())
        .setParameter("version", post.getVersion())
        .setFlushMode(FlushMode.MANUAL)
        .executeUpdate();
    }
}
 
Example 7
@Test
public void testInterceptorWithThreadBoundAndFlushEagerSwitch() throws HibernateException {
	given(session.isOpen()).willReturn(true);
	given(session.getFlushMode()).willReturn(FlushMode.NEVER);

	TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
	HibernateInterceptor interceptor = new HibernateInterceptor();
	interceptor.setFlushMode(HibernateInterceptor.FLUSH_EAGER);
	interceptor.setSessionFactory(sessionFactory);
	try {
		interceptor.invoke(invocation);
	}
	catch (Throwable t) {
		fail("Should not have thrown Throwable: " + t.getMessage());
	}
	finally {
		TransactionSynchronizationManager.unbindResource(sessionFactory);
	}

	InOrder ordered = inOrder(session);
	ordered.verify(session).setFlushMode(FlushMode.AUTO);
	ordered.verify(session).flush();
	ordered.verify(session).setFlushMode(FlushMode.NEVER);
}
 
Example 8
Source Project: quarkus   Source File: JpaTrustedIdentityProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Uni<SecurityIdentity> authenticate(TrustedAuthenticationRequest request,
        AuthenticationRequestContext context) {
    return context.runBlocking(new Supplier<SecurityIdentity>() {
        @Override
        public SecurityIdentity get() {
            // FIXME: unit name
            EntityManager em = jpaConfig.getEntityManagerFactory(null).createEntityManager();
            ((org.hibernate.Session) em).setHibernateFlushMode(FlushMode.MANUAL);
            ((org.hibernate.Session) em).setDefaultReadOnly(true);
            try {
                return authenticate(em, request);
            } catch (SecurityException e) {
                log.debug("Authentication failed", e);
                throw new AuthenticationFailedException();
            } finally {
                em.close();
            }
        }
    });
}
 
Example 9
@Override
protected void prepareForCommit(DefaultTransactionStatus status) {
	if (this.earlyFlushBeforeCommit && status.isNewTransaction()) {
		HibernateTransactionObject txObject = (HibernateTransactionObject) status.getTransaction();
		Session session = txObject.getSessionHolder().getSession();
		if (!session.getFlushMode().lessThan(FlushMode.COMMIT)) {
			logger.debug("Performing an early flush for Hibernate transaction");
			try {
				session.flush();
			}
			catch (HibernateException ex) {
				throw convertHibernateAccessException(ex);
			}
			finally {
				session.setFlushMode(FlushMode.MANUAL);
			}
		}
	}
}
 
Example 10
Source Project: lams   Source File: QueryBinder.java    License: GNU General Public License v2.0 6 votes vote down vote up
private static FlushMode getFlushMode(FlushModeType flushModeType) {
	FlushMode flushMode;
	switch ( flushModeType ) {
		case ALWAYS:
			flushMode = FlushMode.ALWAYS;
			break;
		case AUTO:
			flushMode = FlushMode.AUTO;
			break;
		case COMMIT:
			flushMode = FlushMode.COMMIT;
			break;
		case NEVER:
			flushMode = FlushMode.MANUAL;
			break;
		case MANUAL:
			flushMode = FlushMode.MANUAL;
			break;
		case PERSISTENCE_CONTEXT:
			flushMode = null;
			break;
		default:
			throw new AssertionFailure( "Unknown flushModeType: " + flushModeType );
	}
	return flushMode;
}
 
Example 11
Source Project: spring-analysis-note   Source File: HibernateJpaDialect.java    License: MIT License 5 votes vote down vote up
@Override
public Object prepareTransaction(EntityManager entityManager, boolean readOnly, @Nullable String name)
		throws PersistenceException {

	Session session = getSession(entityManager);
	FlushMode previousFlushMode = prepareFlushMode(session, readOnly);
	return new SessionTransactionData(session, previousFlushMode, null, null);
}
 
Example 12
@Test
public void testUpdateWithLockMode() throws HibernateException {
	TestBean tb = new TestBean();
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);
	hibernateTemplate.update(tb, LockMode.UPGRADE);
	verify(session).update(tb);
	verify(session).lock(tb, LockMode.UPGRADE);
	verify(session).flush();
	verify(session).close();
}
 
Example 13
Source Project: olat   Source File: MarkDAOImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void deleteMark(OLATResourceable ores) {
    StringBuilder sb = new StringBuilder();
    sb.append("delete from ").append(MarkImpl.class.getName()).append(" mark where ").append("mark.resId=:resId and mark.resName=:resName");

    DBQuery query = database.createQuery(sb.toString());
    query.setString("resName", ores.getResourceableTypeName());
    query.setLong("resId", ores.getResourceableId());
    query.executeUpdate(FlushMode.AUTO);
}
 
Example 14
Source Project: spring-analysis-note   Source File: OpenSessionInterceptor.java    License: MIT License 5 votes vote down vote up
/**
 * Open a Session for the given SessionFactory.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @param sessionFactory the SessionFactory to use
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @since 5.0
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	Session session = openSession();
	if (session == null) {
		try {
			session = sessionFactory.openSession();
			session.setFlushMode(FlushMode.MANUAL);
		}
		catch (HibernateException ex) {
			throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
		}
	}
	return session;
}
 
Example 15
@Test
public void testMergeWithEntityName() throws HibernateException {
	TestBean tb = new TestBean();
	TestBean tbMerged = new TestBean();
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);
	given(session.merge("myEntity", tb)).willReturn(tbMerged);
	assertSame(tbMerged, hibernateTemplate.merge("myEntity", tb));
	verify(session).flush();
	verify(session).close();
}
 
Example 16
Source Project: spring-analysis-note   Source File: SpringJtaSessionContext.java    License: MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("deprecation")
protected Session buildOrObtainSession() {
	Session session = super.buildOrObtainSession();
	if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
		session.setFlushMode(FlushMode.MANUAL);
	}
	return session;
}
 
Example 17
@Test
public void testSaveOrUpdateWithFlushModeNever() throws HibernateException {
	TestBean tb = new TestBean();
	given(session.getFlushMode()).willReturn(FlushMode.MANUAL);
	try {
		hibernateTemplate.saveOrUpdate(tb);
		fail("Should have thrown InvalidDataAccessApiUsageException");
	}
	catch (InvalidDataAccessApiUsageException ex) {
		// expected
	}
	verify(session).close();
}
 
Example 18
Source Project: lams   Source File: FlushModeConverter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static String toXml(FlushMode mode) {
	if ( mode == null ) {
		return null;
	}

	// conversely, we want to map MANUAL -> "never" here
	if ( mode == FlushMode.MANUAL ) {
		return "never";
	}

	// todo : what to do if the incoming value does not conform to allowed values?
	// for now, we simply don't deal with that (we write it out).

	return mode.name().toLowerCase( Locale.ENGLISH );
}
 
Example 19
Source Project: robe   Source File: Transaction.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Private constructor
 *
 * @param transactionWrapper {@link TransactionWrapper}
 * @param exceptionHandler   {@link TransactionExceptionHandler}
 * @param flushMode          {@link FlushMode}
 */
private Transaction(TransactionWrapper transactionWrapper, TransactionExceptionHandler exceptionHandler, FlushMode flushMode) {
    this.transactionWrapper = transactionWrapper;
    this.exceptionHandler = exceptionHandler;
    this.flushMode = flushMode;
    storePreviousSession();
    configureNewSession();
    start();
}
 
Example 20
Source Project: lams   Source File: NamedSQLQueryDefinition.java    License: GNU General Public License v2.0 5 votes vote down vote up
NamedSQLQueryDefinition(
		String name,
		String query,
		boolean cacheable,
		String cacheRegion,
		Integer timeout,
		Integer fetchSize,
		FlushMode flushMode,
		CacheMode cacheMode,
		boolean readOnly,
		String comment,
		Map parameterTypes,
		Integer firstResult,
		Integer maxResults,
		String resultSetRef,
		List<String> querySpaces,
		boolean callable,
		NativeSQLQueryReturn[] queryReturns) {
	super(
			name,
			query.trim(), /* trim done to workaround stupid oracle bug that cant handle whitespaces before a { in a sp */
			cacheable,
			cacheRegion,
			timeout,
			null,		// lockOptions
			fetchSize,
			flushMode,
			cacheMode,
			readOnly,
			comment,
			parameterTypes,
			firstResult,
			maxResults
	);
	this.resultSetRef = resultSetRef;
	this.querySpaces = querySpaces;
	this.callable = callable;
	this.queryReturns = queryReturns;
}
 
Example 21
@Test
public void testDeleteWithEntityName()  {
	TestBean tb = new TestBean();
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);
	hibernateTemplate.delete("myEntity", tb);
	verify(session).delete("myEntity", tb);
}
 
Example 22
@Transactional
public T insert(T object) {
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
    sessionFactory.getCurrentSession().save(object);
    sessionFactory.getCurrentSession().flush();
    return object;
}
 
Example 23
@Test
public void testUpdate() throws HibernateException {
	TestBean tb = new TestBean();
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);
	hibernateTemplate.update(tb);
	verify(session).update(tb);
	verify(session).flush();
	verify(session).close();
}
 
Example 24
/**
 * Open a Session for the SessionFactory that this filter uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @param sessionFactory the SessionFactory that this filter uses
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see FlushMode#MANUAL
 */
protected Session openSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
	try {
		Session session = sessionFactory.openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example 25
Source Project: cacheonix-core   Source File: Main.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Demonstrates HQL with runtime fetch strategy
 */
public void viewAllAuctionsSlow() throws Exception {
	System.out.println("Viewing all auction item objects");

	Session s = factory.openSession();
	Transaction tx=null;
	try {
		s.setFlushMode(FlushMode.NEVER); //entirely optional!!
		tx = s.beginTransaction();

		List auctions = s.createQuery(
			"from AuctionItem item "
			+ "left join fetch item.bids bid left join fetch bid.bidder "
			+ "order by item.ends desc"
			)
			.setMaxResults(100)
			.list();

		Iterator iter = new HashSet(auctions).iterator();
		while ( iter.hasNext() ) {
			AuctionItem auction = (AuctionItem) iter.next();
			System.out.println(
				"Auction: " + auction.getId() + " - " + auction.getDescription() +
				", ends: " + auction.getEnds() +
				", bids: " + auction.getBids()
			);
		}
		System.out.println();

		tx.commit();
	}
	catch (Exception e) {
		if (tx!=null) tx.rollback();
		throw e;
	}
	finally {
		s.close();
	}
}
 
Example 26
@Test
public void testMerge()  {
	TestBean tb = new TestBean();
	TestBean tbMerged = new TestBean();
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);
	given(session.merge(tb)).willReturn(tbMerged);
	assertSame(tbMerged, hibernateTemplate.merge(tb));
}
 
Example 27
@Test
@SuppressWarnings("rawtypes")
public void testJtaSessionSynchronization() throws Exception {

	TransactionManager tm = mock(TransactionManager.class);
	MockJtaTransaction transaction = new MockJtaTransaction();
	given(tm.getTransaction()).willReturn(transaction);
	final SessionFactoryImplementor sf = mock(SessionFactoryImplementor.class);
	final Session session = mock(Session.class);
	given(sf.openSession()).willReturn(session);
	given(sf.getTransactionManager()).willReturn(tm);
	given(session.isOpen()).willReturn(true);
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);

	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
	HibernateTemplate ht = new HibernateTemplate(sf);
	ht.setExposeNativeSession(true);
	for (int i = 0; i < 5; i++) {
		ht.executeFind(new HibernateCallback() {

			@Override
			public Object doInHibernate(org.hibernate.Session sess) {
				assertTrue("Has thread session", TransactionSynchronizationManager.hasResource(sf));
				assertEquals(session, sess);
				return null;
			}
		});
	}

	Synchronization synchronization = transaction.getSynchronization();
	assertTrue("JTA synchronization registered", synchronization != null);
	synchronization.beforeCompletion();
	synchronization.afterCompletion(Status.STATUS_COMMITTED);

	assertTrue("Hasn't thread session", !TransactionSynchronizationManager.hasResource(sf));
	assertTrue("JTA synchronizations not active", !TransactionSynchronizationManager.isSynchronizationActive());

	verify(session).flush();
	verify(session).close();
}
 
Example 28
@Transactional
public T insertOrUpdate(T object) {
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
    sessionFactory.getCurrentSession().saveOrUpdate(object);
    sessionFactory.getCurrentSession().flush();
    return object;
}
 
Example 29
Source Project: olat   Source File: ActivityLoggingDaoImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void updateDuration(LoggingObject lastLogObj, long duration) {
    if (db != null && db.isError()) {
        // then we would run into an ERROR when we'd do more with this DB
        // hence we just issue a log.info here with the details
        // @TODO: lower to log.info once we checked that it doesn't occur very often (best for 6.4)
        log.warn("log: DB is in Error state therefore the UserActivityLoggerImpl cannot update the simpleDuration of log_id " + lastLogObj.getKey() + " with value "
                + duration + ", loggingObject: " + lastLogObj);
    } else {
        DBQuery update = db.createQuery("update LoggingObject set simpleDuration = :duration where log_id = :logid");
        update.setLong("duration", duration);
        update.setLong("logid", lastLogObj.getKey());
        // we have to do FlushMode.AUTO (which is the default anyway)
        update.executeUpdate(FlushMode.AUTO);
    }
}
 
Example 30
SQLQueryImpl(
		final String sql,
        final List queryReturns,
        final Collection querySpaces,
        final FlushMode flushMode,
        boolean callable,
        final SessionImplementor session,
        ParameterMetadata parameterMetadata) {
	// TODO : absolutely no usages of this constructor form; can it go away?
	super( sql, flushMode, session, parameterMetadata );
	this.queryReturns = queryReturns;
	this.querySpaces = querySpaces;
	this.callable = callable;
}