Java Code Examples for org.hibernate.FlushMode

The following are top voted examples for showing how to use org.hibernate.FlushMode. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: SpringSessionSynchronization.java   View source code 7 votes vote down vote up
@Override
public void beforeCommit(boolean readOnly) throws DataAccessException {
	if (!readOnly) {
		Session session = getCurrentSession();
		// Read-write transaction -> flush the Hibernate Session.
		// Further check: only flush when not FlushMode.MANUAL.
		if (!session.getFlushMode().equals(FlushMode.MANUAL)) {
			try {
				SessionFactoryUtils.logger.debug("Flushing Hibernate Session on transaction synchronization");
				session.flush();
			}
			catch (HibernateException ex) {
				throw SessionFactoryUtils.convertHibernateAccessException(ex);
			}
		}
	}
}
 
Example 2
Project: lemon   File: SpringSessionSynchronization.java   View source code 6 votes vote down vote up
public void beforeCommit(boolean readOnly) throws DataAccessException {
    if (!readOnly) {
        Session session = getCurrentSession();

        // Read-write transaction -> flush the Hibernate Session.
        // Further check: only flush when not FlushMode.MANUAL.
        if (!FlushMode.isManualFlushMode(session.getFlushMode())) {
            try {
                logger.debug("Flushing Hibernate Session on transaction synchronization");
                session.flush();
            } catch (HibernateException ex) {
                throw SessionFactoryUtils
                        .convertHibernateAccessException(ex);
            }
        }
    }
}
 
Example 3
Project: lams   File: HibernateJpaDialect.java   View source code 6 votes vote down vote up
@Override
public Object prepareTransaction(EntityManager entityManager, boolean readOnly, String name)
		throws PersistenceException {

	Session session = getSession(entityManager);
	FlushMode flushMode = session.getFlushMode();
	FlushMode previousFlushMode = null;
	if (readOnly) {
		// We should suppress flushing for a read-only transaction.
		session.setFlushMode(FlushMode.MANUAL);
		previousFlushMode = flushMode;
	}
	else {
		// We need AUTO or COMMIT for a non-read-only transaction.
		if (flushMode.lessThan(FlushMode.COMMIT)) {
			session.setFlushMode(FlushMode.AUTO);
			previousFlushMode = flushMode;
		}
	}
	return new SessionTransactionData(session, previousFlushMode);
}
 
Example 4
Project: lams   File: SpringSessionSynchronization.java   View source code 6 votes vote down vote up
@Override
public void beforeCommit(boolean readOnly) throws DataAccessException {
	if (!readOnly) {
		Session session = getCurrentSession();
		// Read-write transaction -> flush the Hibernate Session.
		// Further check: only flush when not FlushMode.NEVER/MANUAL.
		if (!session.getFlushMode().lessThan(FlushMode.COMMIT)) {
			try {
				SessionFactoryUtils.logger.debug("Flushing Hibernate Session on transaction synchronization");
				session.flush();
			}
			catch (HibernateException ex) {
				throw translateException(ex);
			}
		}
	}
}
 
Example 5
Project: lams   File: HibernateTransactionManager.java   View source code 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 6
Project: lams   File: QueryBinder.java   View source code 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 7
Project: lams   File: QueryBinder.java   View source code 6 votes vote down vote up
private static FlushMode getFlushMode(AnnotationInstance[] hints, String element, String query) {
	String val = getString( hints, element );
	if ( val == null ) {
		return null;
	}
	if ( val.equalsIgnoreCase( FlushMode.ALWAYS.toString() ) ) {
		return FlushMode.ALWAYS;
	}
	else if ( val.equalsIgnoreCase( FlushMode.AUTO.toString() ) ) {
		return FlushMode.AUTO;
	}
	else if ( val.equalsIgnoreCase( FlushMode.COMMIT.toString() ) ) {
		return FlushMode.COMMIT;
	}
	else if ( val.equalsIgnoreCase( FlushMode.NEVER.toString() ) ) {
		return FlushMode.MANUAL;
	}
	else if ( val.equalsIgnoreCase( FlushMode.MANUAL.toString() ) ) {
		return FlushMode.MANUAL;
	}
	else {
		throw new AnnotationException( "Unknown FlushMode in hint: " + query + ":" + element );
	}
}
 
Example 8
Project: lams   File: NamedQueryLoader.java   View source code 6 votes vote down vote up
@Override
public Object load(Serializable id, Object optionalObject, SessionImplementor session) {
	LOG.debugf( "Loading entity: %s using named query: %s", persister.getEntityName(), queryName );

	// IMPL NOTE: essentially we perform the named query (which loads the entity into the PC), and then
	// do an internal lookup of the entity from the PC.

	final 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( session.generateEntityKey( id, persister ) );

}
 
Example 9
Project: lams   File: NamedQueryCollectionInitializer.java   View source code 6 votes vote down vote up
public void initialize(Serializable key, SessionImplementor session)
throws HibernateException {

       LOG.debugf("Initializing collection: %s using named query: %s", persister.getRole(), queryName);

	//TODO: is there a more elegant way than downcasting?
	AbstractQueryImpl query = (AbstractQueryImpl) session.getNamedSQLQuery(queryName);
	if ( query.getNamedParameters().length>0 ) {
		query.setParameter(
				query.getNamedParameters()[0],
				key,
				persister.getKeyType()
			);
	}
	else {
		query.setParameter( 0, key, persister.getKeyType() );
	}
	query.setCollectionKey( key )
			.setFlushMode( FlushMode.MANUAL )
			.list();

}
 
Example 10
Project: unitimes   File: Department.java   View source code 6 votes vote down vote up
public Department findSameDepartmentInSession(Long newSessionId, org.hibernate.Session hibSession){
	if (newSessionId == null){
		return(null);
	}
	Department newDept = Department.findByDeptCode(this.getDeptCode(), newSessionId, hibSession);
	if (newDept == null && this.getExternalUniqueId() != null){
		// if a department wasn't found and an external uniqueid exists for this 
		//   department check to see if the new term has a department that matches 
		//   the external unique id
		List l = hibSession.
		createCriteria(Department.class).
		add(Restrictions.eq("externalUniqueId",this.getExternalUniqueId())).
		add(Restrictions.eq("session.uniqueId", newSessionId)).
		setFlushMode(FlushMode.MANUAL).
		setCacheable(true).list();

		if (l.size() == 1){
			newDept = (Department) l.get(0);
		}
	}
	return(newDept);
}
 
Example 11
Project: unitimes   File: DepartmentalInstructor.java   View source code 6 votes vote down vote up
public static DepartmentalInstructor findByPuidDepartmentId(String puid, Long deptId, org.hibernate.Session hibSession) {
	try {
	return (DepartmentalInstructor)hibSession.
		createQuery("select d from DepartmentalInstructor d where d.externalUniqueId=:puid and d.department.uniqueId=:deptId").
		setString("puid", puid).
		setLong("deptId",deptId.longValue()).
		setCacheable(true).
		setFlushMode(FlushMode.MANUAL).
		uniqueResult();
	} catch (NonUniqueResultException e) {
		Debug.warning("There are two or more instructors with puid "+puid+" for department "+deptId+" -- returning the first one.");
		return (DepartmentalInstructor)hibSession.
			createQuery("select d from DepartmentalInstructor d where d.externalUniqueId=:puid and d.department.uniqueId=:deptId").
			setString("puid", puid).
			setLong("deptId",deptId.longValue()).
			setCacheable(true).
			setFlushMode(FlushMode.MANUAL).
			list().get(0);
	}
}
 
Example 12
Project: unitimes   File: InstructorSchedulingDatabaseLoader.java   View source code 6 votes vote down vote up
public void load() throws Exception {
	ApplicationProperties.setSessionId(iSessionId);
	org.hibernate.Session hibSession = null;
	Transaction tx = null;
	try {
		hibSession = TimetableManagerDAO.getInstance().createNewSession();
		hibSession.setCacheMode(CacheMode.IGNORE);
		hibSession.setFlushMode(FlushMode.COMMIT);
		
		tx = hibSession.beginTransaction(); 
		
		load(hibSession);
		
		tx.commit();
	} catch (Exception e) {
		iProgress.fatal("Unable to load input data, reason: " + e.getMessage(), e);
		tx.rollback();
	} finally {
		// here we need to close the session since this code may run in a separate thread
		if (hibSession != null && hibSession.isOpen()) hibSession.close();
	}
}
 
Example 13
Project: unitimes   File: TimetableDatabaseLoader.java   View source code 6 votes vote down vote up
public void load() {
	ApplicationProperties.setSessionId(iSessionId);
	org.hibernate.Session hibSession = null;
	Transaction tx = null;
	try {
		hibSession = TimetableManagerDAO.getInstance().getSession();
		hibSession.setCacheMode(CacheMode.IGNORE);
		hibSession.setFlushMode(FlushMode.COMMIT);
		
		tx = hibSession.beginTransaction(); 
		
		load(hibSession);
		
		tx.commit();
	} catch (Exception e) {
		iProgress.message(msglevel("loadFailed", Progress.MSGLEVEL_FATAL), "Unable to load input data, reason:"+e.getMessage(),e);
		tx.rollback();
	} finally {
		// here we need to close the session since this code may run in a separate thread
		if (hibSession!=null && hibSession.isOpen()) hibSession.close();
	}
}
 
Example 14
Project: unitimes   File: EventImport.java   View source code 6 votes vote down vote up
private Room findRoom(String buildingAbbv, String roomNumber){
	Room room = null;
	if (room == null) {
		List rooms =  this.
		getHibSession().
		createQuery("select distinct r from Room as r where r.roomNumber=:roomNbr and r.building.abbreviation = :building").
		setString("building", buildingAbbv).
		setString("roomNbr", roomNumber).
		setCacheable(true).
		setFlushMode(FlushMode.MANUAL).
		list();
		if (rooms != null && rooms.size() > 0){
			room = (Room) rooms.iterator().next();
		}
	}
	return(room);
}
 
Example 15
Project: spring4-understanding   File: HibernateJpaDialect.java   View source code 6 votes vote down vote up
protected FlushMode prepareFlushMode(Session session, boolean readOnly) throws PersistenceException {
	FlushMode flushMode = session.getFlushMode();
	if (readOnly) {
		// We should suppress flushing for a read-only transaction.
		if (!flushMode.equals(FlushMode.MANUAL)) {
			session.setFlushMode(FlushMode.MANUAL);
			return flushMode;
		}
	}
	else {
		// We need AUTO or COMMIT for a non-read-only transaction.
		if (flushMode.lessThan(FlushMode.COMMIT)) {
			session.setFlushMode(FlushMode.AUTO);
			return flushMode;
		}
	}
	// No FlushMode change needed...
	return null;
}
 
Example 16
Project: spring4-understanding   File: SpringSessionSynchronization.java   View source code 6 votes vote down vote up
@Override
public void beforeCommit(boolean readOnly) throws DataAccessException {
	if (!readOnly) {
		Session session = getCurrentSession();
		// Read-write transaction -> flush the Hibernate Session.
		// Further check: only flush when not FlushMode.NEVER/MANUAL.
		if (!session.getFlushMode().lessThan(FlushMode.COMMIT)) {
			try {
				SessionFactoryUtils.logger.debug("Flushing Hibernate Session on transaction synchronization");
				session.flush();
			}
			catch (HibernateException ex) {
				throw translateException(ex);
			}
		}
	}
}
 
Example 17
Project: spring4-understanding   File: HibernateTransactionManager.java   View source code 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 18
Project: spring4-understanding   File: OpenSessionInViewTests.java   View source code 6 votes vote down vote up
@Test
public void testOpenSessionInterceptor() throws Exception {
	final SessionFactory sf = mock(SessionFactory.class);
	final Session session = mock(Session.class);

	OpenSessionInterceptor interceptor = new OpenSessionInterceptor();
	interceptor.setSessionFactory(sf);

	Runnable tb = new Runnable() {
		@Override
		public void run() {
			assertTrue(TransactionSynchronizationManager.hasResource(sf));
			assertEquals(session, SessionFactoryUtils.getSession(sf, false));
		}
	};
	ProxyFactory pf = new ProxyFactory(tb);
	pf.addAdvice(interceptor);
	Runnable tbProxy = (Runnable) pf.getProxy();

	given(sf.openSession()).willReturn(session);
	given(session.isOpen()).willReturn(true);
	tbProxy.run();
	verify(session).setFlushMode(FlushMode.MANUAL);
	verify(session).close();
}
 
Example 19
Project: spring4-understanding   File: HibernateInterceptorTests.java   View source code 6 votes vote down vote up
@Test
public void testInterceptorWithThreadBoundAndFlushEager() throws HibernateException {
	given(session.isOpen()).willReturn(true);
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);

	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);
	}

	verify(session).flush();
}
 
Example 20
Project: spring4-understanding   File: HibernateInterceptorTests.java   View source code 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 21
Project: spring4-understanding   File: HibernateInterceptorTests.java   View source code 6 votes vote down vote up
@Test
public void testInterceptorWithThreadBoundAndFlushCommit() {
	given(session.isOpen()).willReturn(true);
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);

	TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
	HibernateInterceptor interceptor = new HibernateInterceptor();
	interceptor.setSessionFactory(sessionFactory);
	interceptor.setFlushMode(HibernateInterceptor.FLUSH_COMMIT);
	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.COMMIT);
	ordered.verify(session).setFlushMode(FlushMode.AUTO);
	verify(session, never()).flush();
}
 
Example 22
Project: spring4-understanding   File: HibernateInterceptorTests.java   View source code 6 votes vote down vote up
@Test
public void testInterceptorWithThreadBoundAndFlushAlways() {
	given(session.isOpen()).willReturn(true);
	given(session.getFlushMode()).willReturn(FlushMode.AUTO);

	TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
	HibernateInterceptor interceptor = new HibernateInterceptor();
	interceptor.setSessionFactory(sessionFactory);
	interceptor.setFlushMode(HibernateInterceptor.FLUSH_ALWAYS);
	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.ALWAYS);
	ordered.verify(session).setFlushMode(FlushMode.AUTO);
	verify(session, never()).flush();
}
 
Example 23
Project: spring4-understanding   File: SpringSessionSynchronization.java   View source code 6 votes vote down vote up
@Override
public void beforeCommit(boolean readOnly) throws DataAccessException {
	if (!readOnly) {
		Session session = getCurrentSession();
		// Read-write transaction -> flush the Hibernate Session.
		// Further check: only flush when not FlushMode.MANUAL.
		if (!session.getFlushMode().equals(FlushMode.MANUAL)) {
			try {
				SessionFactoryUtils.logger.debug("Flushing Hibernate Session on transaction synchronization");
				session.flush();
			}
			catch (HibernateException ex) {
				throw SessionFactoryUtils.convertHibernateAccessException(ex);
			}
		}
	}
}
 
Example 24
Project: spring4-understanding   File: SpringSessionSynchronization.java   View source code 6 votes vote down vote up
@Override
public void beforeCommit(boolean readOnly) throws DataAccessException {
	if (!readOnly) {
		Session session = getCurrentSession();
		// Read-write transaction -> flush the Hibernate Session.
		// Further check: only flush when not FlushMode.MANUAL.
		if (!session.getFlushMode().equals(FlushMode.MANUAL)) {
			try {
				SessionFactoryUtils.logger.debug("Flushing Hibernate Session on transaction synchronization");
				session.flush();
			}
			catch (HibernateException ex) {
				throw SessionFactoryUtils.convertHibernateAccessException(ex);
			}
		}
	}
}
 
Example 25
Project: lemon   File: SpringSessionContext.java   View source code 5 votes vote down vote up
public Session currentSession() throws HibernateException {
    Object value = TransactionSynchronizationManager
            .getResource(this.sessionFactory);

    if (value instanceof Session) {
        return (Session) value;
    } else if (value instanceof SessionHolder) {
        SessionHolder sessionHolder = (SessionHolder) value;
        Session session = sessionHolder.getSession();

        if (TransactionSynchronizationManager.isSynchronizationActive()
                && !sessionHolder.isSynchronizedWithTransaction()) {
            TransactionSynchronizationManager
                    .registerSynchronization(new SpringSessionSynchronization(
                            sessionHolder, this.sessionFactory));
            sessionHolder.setSynchronizedWithTransaction(true);

            // Switch to FlushMode.AUTO, as we have to assume a thread-bound Session
            // with FlushMode.MANUAL, which needs to allow flushing within the transaction.
            FlushMode flushMode = session.getFlushMode();

            if (FlushMode.isManualFlushMode(flushMode)
                    && !TransactionSynchronizationManager
                            .isCurrentTransactionReadOnly()) {
                session.setFlushMode(FlushMode.AUTO);
                sessionHolder.setPreviousFlushMode(flushMode);
            }
        }

        return session;
    } else {
        throw new HibernateException("No Session found for current thread");
    }
}
 
Example 26
Project: lams   File: OpenSessionInterceptor.java   View source code 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 org.hibernate.FlushMode#MANUAL
 */
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 27
Project: lams   File: OpenSessionInViewInterceptor.java   View source code 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 org.hibernate.FlushMode#MANUAL
 */
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 28
Project: lams   File: OpenSessionInViewFilter.java   View source code 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 org.hibernate.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 29
Project: lams   File: SpringJtaSessionContext.java   View source code 5 votes vote down vote up
@Override
protected Session buildOrObtainSession() {
	Session session = super.buildOrObtainSession();
	if (TransactionSynchronizationManager.isCurrentTransactionReadOnly()) {
		session.setFlushMode(FlushMode.MANUAL);
	}
	return session;
}
 
Example 30
Project: lams   File: OpenSessionInterceptor.java   View source code 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 org.hibernate.FlushMode#MANUAL
 */
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 31
Project: lams   File: SessionFactoryUtils.java   View source code 5 votes vote down vote up
/**
 * Close the given Session or register it for deferred close.
 * @param session the Hibernate Session to close
 * @param sessionFactory Hibernate SessionFactory that the Session was created with
 * (may be {@code null})
 * @see #initDeferredClose
 * @see #processDeferredClose
 */
static void closeSessionOrRegisterDeferredClose(Session session, SessionFactory sessionFactory) {
	Map<SessionFactory, Set<Session>> holderMap = deferredCloseHolder.get();
	if (holderMap != null && sessionFactory != null && holderMap.containsKey(sessionFactory)) {
		logger.debug("Registering Hibernate Session for deferred close");
		// Switch Session to FlushMode.MANUAL for remaining lifetime.
		session.setFlushMode(FlushMode.MANUAL);
		Set<Session> sessions = holderMap.get(sessionFactory);
		sessions.add(session);
	}
	else {
		closeSession(session);
	}
}
 
Example 32
Project: lams   File: HbmBinder.java   View source code 5 votes vote down vote up
private static void bindNamedQuery(Element queryElem, String path, Mappings mappings) {
	String queryName = queryElem.attributeValue( "name" );
	if (path!=null) queryName = path + '.' + queryName;
	String query = queryElem.getText();
	LOG.debugf( "Named query: %s -> %s", queryName, query );

	boolean cacheable = "true".equals( queryElem.attributeValue( "cacheable" ) );
	String region = queryElem.attributeValue( "cache-region" );
	Attribute tAtt = queryElem.attribute( "timeout" );
	Integer timeout = tAtt == null ? null : Integer.valueOf( tAtt.getValue() );
	Attribute fsAtt = queryElem.attribute( "fetch-size" );
	Integer fetchSize = fsAtt == null ? null : Integer.valueOf( fsAtt.getValue() );
	Attribute roAttr = queryElem.attribute( "read-only" );
	boolean readOnly = roAttr != null && "true".equals( roAttr.getValue() );
	Attribute cacheModeAtt = queryElem.attribute( "cache-mode" );
	String cacheMode = cacheModeAtt == null ? null : cacheModeAtt.getValue();
	Attribute cmAtt = queryElem.attribute( "comment" );
	String comment = cmAtt == null ? null : cmAtt.getValue();

	NamedQueryDefinition namedQuery = new NamedQueryDefinitionBuilder().setName( queryName )
			.setQuery( query )
			.setCacheable( cacheable )
			.setCacheRegion( region )
			.setTimeout( timeout )
			.setFetchSize( fetchSize )
			.setFlushMode( FlushMode.interpretExternalSetting( queryElem.attributeValue( "flush-mode" ) ) )
			.setCacheMode( CacheMode.interpretExternalSetting( cacheMode ) )
			.setReadOnly( readOnly )
			.setComment( comment )
			.setParameterTypes( getParameterTypes( queryElem ) )
			.createNamedQueryDefinition();

	mappings.addQuery( namedQuery.getName(), namedQuery );
}
 
Example 33
Project: lams   File: QueryHintDefinition.java   View source code 5 votes vote down vote up
public FlushMode getFlushMode(String query) {
	String hitName = QueryHints.FLUSH_MODE;
	String value =(String)  hintsMap.get( hitName );
	if ( value == null ) {
		return null;
	}
	try {
		return FlushMode.interpretExternalSetting( value );
	}
	catch ( MappingException e ) {
		throw new AnnotationException( "Unknown FlushMode in hint: " + query + ":" + hitName, e );
	}
}
 
Example 34
Project: lams   File: QueryBinder.java   View source code 5 votes vote down vote up
public static void bindQuery(org.hibernate.annotations.NamedQuery queryAnn, Mappings mappings) {
	if ( queryAnn == null ) return;
	if ( BinderHelper.isEmptyAnnotationValue( queryAnn.name() ) ) {
		throw new AnnotationException( "A named query must have a name when used in class or package level" );
	}
	FlushMode flushMode;
	flushMode = getFlushMode( queryAnn.flushMode() );

	NamedQueryDefinition query = new NamedQueryDefinitionBuilder().setName( queryAnn.name() )
			.setQuery( queryAnn.query() )
			.setCacheable( queryAnn.cacheable() )
			.setCacheRegion(
					BinderHelper.isEmptyAnnotationValue( queryAnn.cacheRegion() ) ?
							null :
							queryAnn.cacheRegion()
			)
			.setTimeout( queryAnn.timeout() < 0 ? null : queryAnn.timeout() )
			.setFetchSize( queryAnn.fetchSize() < 0 ? null : queryAnn.fetchSize() )
			.setFlushMode( flushMode )
			.setCacheMode( getCacheMode( queryAnn.cacheMode() ) )
			.setReadOnly( queryAnn.readOnly() )
			.setComment( BinderHelper.isEmptyAnnotationValue( queryAnn.comment() ) ? null : queryAnn.comment() )
			.setParameterTypes( null )
			.createNamedQueryDefinition();

	mappings.addQuery( query.getName(), query );
	if ( LOG.isDebugEnabled() ) {
		LOG.debugf( "Binding named query: %s => %s", query.getName(), query.getQueryString() );
	}
}
 
Example 35
Project: lams   File: NamedSQLQueryDefinition.java   View source code 5 votes vote down vote up
/**
 * This form was initially used to construct a NamedSQLQueryDefinition from the binder code when a the
 * result-set mapping information is not explicitly  provided in the query definition
 * (i.e., no resultset-mapping used).
 *
 * @param name The name of named query
 * @param query The sql query string
 * @param queryReturns The in-lined query return definitions
 * @param querySpaces Any specified query spaces (used for auto-flushing)
 * @param cacheable Whether the query results are cacheable
 * @param cacheRegion If cacheable, the region into which to store the results
 * @param timeout A JDBC-level timeout to be applied
 * @param fetchSize A JDBC-level fetch-size to be applied
 * @param flushMode The flush mode to use for this query
 * @param cacheMode The cache mode to use during execution and subsequent result loading
 * @param readOnly Whether returned entities should be marked as read-only in the session
 * @param comment Any sql comment to be applied to the query
 * @param parameterTypes parameter type map
 * @param callable Does the query string represent a callable object (i.e., proc)
 *
 * @deprecated Use {@link NamedSQLQueryDefinitionBuilder} instead.
 */
@Deprecated
public NamedSQLQueryDefinition(
		String name,
		String query,
		NativeSQLQueryReturn[] queryReturns,
		List<String> querySpaces,
		boolean cacheable,
		String cacheRegion,
		Integer timeout,
		Integer fetchSize,
		FlushMode flushMode,
		CacheMode cacheMode,
		boolean readOnly,
		String comment,
		Map parameterTypes,
		boolean callable) {
	this(
			name,
			query,
			cacheable,
			cacheRegion,
			timeout,
			fetchSize,
			flushMode,
			cacheMode,
			readOnly,
			comment,
			parameterTypes,
			null,		// firstResult
			null,		// maxResults
			null, 		// resultSetRef
			querySpaces,
			callable,
			queryReturns
	);
}
 
Example 36
Project: lams   File: NamedSQLQueryDefinition.java   View source code 5 votes vote down vote up
/**
 * This form was initially used to construct a NamedSQLQueryDefinition from the binder code when a
 * resultset-mapping reference is used.
 *
 * @param name The name of named query
 * @param query The sql query string
 * @param resultSetRef The resultset-mapping name
 * @param querySpaces Any specified query spaces (used for auto-flushing)
 * @param cacheable Whether the query results are cacheable
 * @param cacheRegion If cacheable, the region into which to store the results
 * @param timeout A JDBC-level timeout to be applied
 * @param fetchSize A JDBC-level fetch-size to be applied
 * @param flushMode The flush mode to use for this query
 * @param cacheMode The cache mode to use during execution and subsequent result loading
 * @param readOnly Whether returned entities should be marked as read-only in the session
 * @param comment Any sql comment to be applied to the query
 * @param parameterTypes parameter type map
 * @param callable Does the query string represent a callable object (i.e., proc)
 *
 * @deprecated Use {@link NamedSQLQueryDefinitionBuilder} instead.
 */
@Deprecated
public NamedSQLQueryDefinition(
		String name,
		String query,
		String resultSetRef,
		List<String> querySpaces,
		boolean cacheable,
		String cacheRegion,
		Integer timeout,
		Integer fetchSize,
		FlushMode flushMode,
		CacheMode cacheMode,
		boolean readOnly,
		String comment,
		Map parameterTypes,
		boolean callable) {

	this(
			name,
			query,
			cacheable,
			cacheRegion,
			timeout,
			fetchSize,
			flushMode,
			cacheMode,
			readOnly,
			comment,
			parameterTypes,
			null,		// firstResult
			null,		// maxResults
			resultSetRef,
			querySpaces,
			callable,
			null		// queryReturns
	);
}
 
Example 37
Project: lams   File: NamedSQLQueryDefinition.java   View source code 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 38
Project: lams   File: NamedQueryDefinition.java   View source code 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 39
Project: lams   File: NamedQueryDefinition.java   View source code 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 40
Project: lams   File: NamedQueryDefinition.java   View source code 5 votes vote down vote up
NamedQueryDefinition(
		String name,
		String query,
		boolean cacheable,
		String cacheRegion,
		Integer timeout,
		LockOptions lockOptions,
		Integer fetchSize,
		FlushMode flushMode,
		CacheMode cacheMode,
		boolean readOnly,
		String comment,
		Map parameterTypes,
		Integer firstResult,
		Integer maxResults) {
	this.name = name;
	this.query = query;
	this.cacheable = cacheable;
	this.cacheRegion = cacheRegion;
	this.timeout = timeout;
	this.lockOptions = lockOptions;
	this.fetchSize = fetchSize;
	this.flushMode = flushMode;
	this.parameterTypes = parameterTypes;
	this.cacheMode = cacheMode;
	this.readOnly = readOnly;
	this.comment = comment;

	this.firstResult = firstResult;
	this.maxResults = maxResults;
}