org.hibernate.FlushMode Java Examples

The following examples show how to use org.hibernate.FlushMode. 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: JpaIdentityProvider.java    From quarkus with 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 File: MutinySessionImpl.java    From hibernate-reactive with GNU Lesser General Public License v2.1 6 votes vote down vote up
@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 #3
Source File: CacheHibernateBlobStoreSelfTest.java    From ignite with 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 #4
Source File: QueryBinder.java    From lams with 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 #5
Source File: HibernateInterceptorTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: HibernateTransactionManager.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #7
Source File: FlushModeConverter.java    From lams with 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 #8
Source File: JpaTrustedIdentityProvider.java    From quarkus with 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
Source File: EntityReplicationTest.java    From high-performance-java-persistence with Apache License 2.0 6 votes vote down vote up
@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 #10
Source File: SessionFactoryImpl.java    From lams with 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 #11
Source File: NamedQueryDefinition.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This version is used to bind named queries defined via {@link javax.persistence.NamedQuery}.
 *
 * @param name The name under which to key/register the query
 * @param query The query string.
 * @param cacheable Is the query cacheable?
 * @param cacheRegion If cacheable, was there a specific region named?
 * @param timeout Query timeout, {@code null} indicates no timeout
 * @param lockTimeout Specifies the lock timeout for queries that apply lock modes.
 * @param fetchSize Fetch size associated with the query, {@code null} indicates no limit
 * @param flushMode Flush mode associated with query
 * @param cacheMode Cache mode associated with query
 * @param readOnly Should entities returned from this query (those not already associated with the Session anyway)
 * 		be loaded as read-only?
 * @param comment SQL comment to be used in the generated SQL, {@code null} indicates none
 * @param parameterTypes (no idea, afaict this is always passed as null)
 *
 * @deprecated Use {@link NamedQueryDefinitionBuilder} instead.
 */
@Deprecated
public NamedQueryDefinition(
		String name,
		String query,
		boolean cacheable,
		String cacheRegion,
		Integer timeout,
		Integer lockTimeout,
		Integer fetchSize,
		FlushMode flushMode,
		CacheMode cacheMode,
		boolean readOnly,
		String comment,
		Map parameterTypes) {
	this(
			name,
			query,
			cacheable,
			cacheRegion,
			timeout,
			new LockOptions().setTimeOut( lockTimeout ),
			fetchSize,
			flushMode,
			cacheMode,
			readOnly,
			comment,
			parameterTypes,
			null,		// firstResult
			null		// maxResults
	);
}
 
Example #12
Source File: OpenSessionInterceptor.java    From java-technology-stack with 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 #13
Source File: UserResource.java    From robe with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns a single User matches with the given id.
 * <p>
 * Status Code:
 * Not Found  404
 *
 * @param credentials injected by {@link RobeAuth} annotation for authentication.
 * @param id          This is the oid of {@link User}
 * @return a {@link User} resource matches with the given id.
 */
@RobeService(group = "User", description = "Returns a User resource matches with the given id.")
@Path("{id}")
@GET
@UnitOfWork(readOnly = true, cacheMode = CacheMode.GET, flushMode = FlushMode.MANUAL)
public User get(@RobeAuth Credentials credentials, @PathParam("id") String id) {
    User entity = userDao.findById(id);
    if (entity == null) {
        throw new WebApplicationException(Response.status(404).build());
    }
    return entity;
}
 
Example #14
Source File: TreeIntercptor.java    From Lottery with GNU General Public License v2.0 5 votes vote down vote up
@Override
public void onDelete(Object entity, Serializable id, Object[] state,
		String[] propertyNames, Type[] types) {
	if (entity instanceof HibernateTree) {
		HibernateTree<?> tree = (HibernateTree<?>) entity;
		String beanName = tree.getClass().getName();
		Session session = getSession();
		FlushMode model = session.getFlushMode();
		session.setFlushMode(FlushMode.MANUAL);
		String hql = "select bean." + tree.getLftName() + " from "
				+ beanName + " bean where bean.id=:id";
		Integer myPosition = ((Number) session.createQuery(hql)
				.setParameter("id", tree.getId()).uniqueResult())
				.intValue();
		String hql1 = "update " + beanName + " bean set bean."
				+ tree.getRgtName() + " = bean." + tree.getRgtName()
				+ " - 2 WHERE bean." + tree.getRgtName() + " > :myPosition";
		String hql2 = "update " + beanName + " bean set bean."
				+ tree.getLftName() + " = bean." + tree.getLftName()
				+ " - 2 WHERE bean." + tree.getLftName() + " > :myPosition";
		if (!StringUtils.isBlank(tree.getTreeCondition())) {
			hql1 += " and (" + tree.getTreeCondition() + ")";
			hql2 += " and (" + tree.getTreeCondition() + ")";
		}
		session.createQuery(hql1).setInteger("myPosition", myPosition)
				.executeUpdate();
		session.createQuery(hql2).setInteger("myPosition", myPosition)
				.executeUpdate();
		session.setFlushMode(model);
	}
}
 
Example #15
Source File: NamedQueryLoader.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public Object load(Serializable id, Object optionalObject, SessionImplementor session) 
throws HibernateException {
	
	if ( log.isDebugEnabled() ) {
		log.debug(
				"loading entity: " + persister.getEntityName() + 
				" using named query: " + queryName 
			);
	}
	
	AbstractQueryImpl query = (AbstractQueryImpl) session.getNamedQuery(queryName);
	if ( query.hasNamedParameters() ) {
		query.setParameter( 
				query.getNamedParameters()[0], 
				id, 
				persister.getIdentifierType() 
			);
	}
	else {
		query.setParameter( 0, id, persister.getIdentifierType() );
	}
	query.setOptionalId(id);
	query.setOptionalEntityName( persister.getEntityName() );
	query.setOptionalObject(optionalObject);
	query.setFlushMode( FlushMode.MANUAL );
	query.list();
	
	// now look up the object we are really interested in!
	// (this lets us correctly handle proxies and multi-row
	// or multi-column queries)
	return session.getPersistenceContext()
			.getEntity( new EntityKey( id, persister, session.getEntityMode() ) );

}
 
Example #16
Source File: HibernateJpaDialect.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Object beginTransaction(EntityManager entityManager, TransactionDefinition definition)
		throws PersistenceException, SQLException, TransactionException {

	Session session = getSession(entityManager);

	if (definition.getTimeout() != TransactionDefinition.TIMEOUT_DEFAULT) {
		session.getTransaction().setTimeout(definition.getTimeout());
	}

	boolean isolationLevelNeeded = (definition.getIsolationLevel() != TransactionDefinition.ISOLATION_DEFAULT);
	Integer previousIsolationLevel = null;
	Connection preparedCon = null;

	if (isolationLevelNeeded || definition.isReadOnly()) {
		if (this.prepareConnection) {
			preparedCon = HibernateConnectionHandle.doGetConnection(session);
			previousIsolationLevel = DataSourceUtils.prepareConnectionForTransaction(preparedCon, definition);
		}
		else if (isolationLevelNeeded) {
			throw new InvalidIsolationLevelException(getClass().getSimpleName() +
					" does not support custom isolation levels since the 'prepareConnection' flag is off. " +
					"This is the case on Hibernate 3.6 by default; either switch that flag at your own risk " +
					"or upgrade to Hibernate 4.x, with 4.2+ recommended.");
		}
	}

	// Standard JPA transaction begin call for full JPA context setup...
	entityManager.getTransaction().begin();

	// Adapt flush mode and store previous isolation level, if any.
	FlushMode previousFlushMode = prepareFlushMode(session, definition.isReadOnly());
	return new SessionTransactionData(session, previousFlushMode, preparedCon, previousIsolationLevel);
}
 
Example #17
Source File: AbstractSaveEventListener.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private static boolean shouldDelayIdentityInserts(
		boolean requiresImmediateIdAccess,
		boolean partOfTransaction,
		FlushMode flushMode) {
	if ( requiresImmediateIdAccess ) {
		// todo : make this configurable?  as a way to support this behavior with Session#save etc
		return false;
	}

	// otherwise we should delay the IDENTITY insertions if either:
	//		1) we are not part of a transaction
	//		2) we are in FlushMode MANUAL or COMMIT (not AUTO nor ALWAYS)
	return !partOfTransaction || flushMode == MANUAL || flushMode == COMMIT;

}
 
Example #18
Source File: SessionImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean shouldDoManagedFlush(SessionImplementor session) {
	if ( session.isClosed() ) {
		return false;
	}
	return session.getHibernateFlushMode() != FlushMode.MANUAL;
}
 
Example #19
Source File: NamedQueryDefinition.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This form is used to bind named queries from Hibernate metadata, both {@code hbm.xml} files and
 * {@link org.hibernate.annotations.NamedQuery} annotation.
 *
 * @param name The name under which to key/register the query
 * @param query The query string.
 * @param cacheable Is the query cacheable?
 * @param cacheRegion If cacheable, was there a specific region named?
 * @param timeout Query timeout, {@code null} indicates no timeout
 * @param fetchSize Fetch size associated with the query, {@code null} indicates no limit
 * @param flushMode Flush mode associated with query
 * @param cacheMode Cache mode associated with query
 * @param readOnly Should entities returned from this query (those not already associated with the Session anyway)
 * 		be loaded as read-only?
 * @param comment SQL comment to be used in the generated SQL, {@code null} indicates none
 * @param parameterTypes (no idea, afaict this is always passed as null)
 *
 * @deprecated Use {@link NamedQueryDefinitionBuilder} instead.
 */
@Deprecated
public NamedQueryDefinition(
		String name,
		String query,
		boolean cacheable,
		String cacheRegion,
		Integer timeout,
		Integer fetchSize,
		FlushMode flushMode,
		CacheMode cacheMode,
		boolean readOnly,
		String comment,
		Map parameterTypes) {
	this(
			name,
			query,
			cacheable,
			cacheRegion,
			timeout,
			LockOptions.WAIT_FOREVER,
			fetchSize,
			flushMode,
			cacheMode,
			readOnly,
			comment,
			parameterTypes
	);
}
 
Example #20
Source File: HibernateJtaTransactionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #21
Source File: HibernateTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testSaveOrUpdateWithEntityName() throws HibernateException {
	TestBean tb = new TestBean();

	given(session.getFlushMode()).willReturn(FlushMode.AUTO);
	hibernateTemplate.saveOrUpdate("myEntity", tb);
	verify(session).saveOrUpdate("myEntity", tb);
	verify(session).flush();
	verify(session).close();
}
 
Example #22
Source File: SQLQueryImpl.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
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;
}
 
Example #23
Source File: ActivityLoggingDaoImpl.java    From olat with 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 #24
Source File: BaseHibernateJPARepository.java    From spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework with MIT License 5 votes vote down vote up
@Transactional
public T insertOrUpdate(T object) {
    sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
    sessionFactory.getCurrentSession().saveOrUpdate(object);
    sessionFactory.getCurrentSession().flush();
    return object;
}
 
Example #25
Source File: HibernateTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #26
Source File: Main.java    From cacheonix-core with 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 #27
Source File: OpenSessionInViewFilter.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #28
Source File: HibernateTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteAll() throws HibernateException {
	TestBean tb1 = new TestBean();
	TestBean tb2 = new TestBean();
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);
	List tbs = new ArrayList();
	tbs.add(tb1);
	tbs.add(tb2);
	hibernateTemplate.deleteAll(tbs);
	verify(session).delete(same(tb1));
	verify(session).delete(same(tb2));
	verify(session).flush();
	verify(session).close();
}
 
Example #29
Source File: OpenSessionInViewInterceptor.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Open a Session for the SessionFactory that this interceptor uses.
 * <p>The default implementation delegates to the {@link SessionFactory#openSession}
 * method and sets the {@link Session}'s flush mode to "MANUAL".
 * @return the Session to use
 * @throws DataAccessResourceFailureException if the Session could not be created
 * @see FlushMode#MANUAL
 */
@SuppressWarnings("deprecation")
protected Session openSession() throws DataAccessResourceFailureException {
	try {
		Session session = getSessionFactory().openSession();
		session.setFlushMode(FlushMode.MANUAL);
		return session;
	}
	catch (HibernateException ex) {
		throw new DataAccessResourceFailureException("Could not open Hibernate Session", ex);
	}
}
 
Example #30
Source File: HibernateTemplateTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testSave()  {
	TestBean tb = new TestBean();
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);
	given(session.save(tb)).willReturn(0);
	assertEquals("Correct return value", hibernateTemplate.save(tb), 0);
}