Java Code Examples for org.hibernate.LockMode

The following are top voted examples for showing how to use org.hibernate.LockMode. 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: TwoPhaseLoad.java   View source code 6 votes vote down vote up
/**
 * Add an uninitialized instance of an entity class, as a placeholder to ensure object
 * identity. Must be called before <tt>postHydrate()</tt>.
 *
 * Create a "temporary" entry for a newly instantiated entity. The entity is uninitialized,
 * but we need the mapping from id to instance in order to guarantee uniqueness.
 *
 * @param key The entity key
 * @param object The entity instance
 * @param persister The entity persister
 * @param lockMode The lock mode
 * @param lazyPropertiesAreUnFetched Are lazy properties still un-fetched?
 * @param session The Session
 */
public static void addUninitializedEntity(
		final EntityKey key,
		final Object object,
		final EntityPersister persister,
		final LockMode lockMode,
		final boolean lazyPropertiesAreUnFetched,
		final SessionImplementor session) {
	session.getPersistenceContext().addEntity(
			object,
			Status.LOADING,
			null,
			key,
			null,
			lockMode,
			true,
			persister,
			false,
			lazyPropertiesAreUnFetched
	);
}
 
Example 2
Project: lams   File: TimesTenDialect.java   View source code 6 votes vote down vote up
@Override
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
	// TimesTen has no known variation of a "SELECT ... FOR UPDATE" syntax...
	if ( lockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT ) {
		return new PessimisticForceIncrementLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode == LockMode.PESSIMISTIC_WRITE ) {
		return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode == LockMode.PESSIMISTIC_READ ) {
		return new PessimisticReadUpdateLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode == LockMode.OPTIMISTIC ) {
		return new OptimisticLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode == LockMode.OPTIMISTIC_FORCE_INCREMENT ) {
		return new OptimisticForceIncrementLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode.greaterThan( LockMode.READ ) ) {
		return new UpdateLockingStrategy( lockable, lockMode );
	}
	else {
		return new SelectLockingStrategy( lockable, lockMode );
	}
}
 
Example 3
Project: ctsms   File: ProbandServiceImpl.java   View source code 6 votes vote down vote up
@Override
protected ProbandAddressOutVO handleDeleteProbandAddress(
		AuthenticationVO auth, Long probandAddressId) throws Exception {
	ProbandAddressDao addressDao = this.getProbandAddressDao();
	ProbandAddress address = CheckIDUtil.checkProbandAddressId(probandAddressId, addressDao);
	Proband proband = address.getProband();
	this.getProbandDao().lock(proband, LockMode.PESSIMISTIC_WRITE);
	// Proband proband = ServiceUtil.checkProbandId(address.getProband().getId(), this.getProbandDao(), LockMode.PESSIMISTIC_WRITE); // address.getProband();
	ProbandAddressOutVO result = addressDao.toProbandAddressOutVO(address);
	if (!result.isDecrypted()) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_PROBAND_ADDRESS);
	}
	ServiceUtil.checkProbandLocked(proband);
	if (address.isWireTransfer() && addressDao.getCount(address.getProband().getId(), null, null, null) > 1) { // proband.getAddresses().Xsize() > 1) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DELETE_WIRE_TRANSFER_PROBAND_ADDRESS);
	}
	proband.removeAddresses(address);
	address.setProband(null);
	addressDao.remove(address);
	Timestamp now = new Timestamp(System.currentTimeMillis());
	User user = CoreUtil.getUser();
	ServiceUtil.logSystemMessage(proband, result.getProband(), now, user, SystemMessageCodes.PROBAND_ADDRESS_DELETED, result, null, this.getJournalEntryDao());
	return result;
}
 
Example 4
Project: lams   File: HibernateTemplate.java   View source code 6 votes vote down vote up
@Override
public Object get(final String entityName, final Serializable id, final LockMode lockMode)
		throws DataAccessException {

	return executeWithNativeSession(new HibernateCallback<Object>() {
		@Override
		public Object doInHibernate(Session session) throws HibernateException {
			if (lockMode != null) {
				return session.get(entityName, id, new LockOptions(lockMode));
			}
			else {
				return session.get(entityName, id);
			}
		}
	});
}
 
Example 5
Project: ctsms   File: FileServiceImpl.java   View source code 6 votes vote down vote up
/**
 * @see org.phoenixctms.ctsms.service.shared.FileService#updateFile(FileInVO, FileContentInVO)
 */
@Override
protected FileOutVO handleUpdateFile(AuthenticationVO auth, FileInVO modifiedFile, FileContentInVO modifiedFileContent)
		throws Exception
		{
	FileDao fileDao = this.getFileDao();
	File originalFile = CheckIDUtil.checkFileId(modifiedFile.getId(), fileDao, LockMode.UPGRADE_NOWAIT);
	checkFileInput(modifiedFile);
	if (!fileDao.toFileOutVO(originalFile).isDecrypted()) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_FILE);
	}
	FileOutVO original = fileDao.toFileOutVO(originalFile);
	fileDao.evict(originalFile);
	File file = fileDao.fileInVOToEntity(modifiedFile);
	Timestamp now = new Timestamp(System.currentTimeMillis());
	User user = CoreUtil.getUser();
	CoreUtil.modifyVersion(originalFile, file, now, user);
	saveFileContent(file, modifiedFileContent);
	fileDao.update(file);
	return addFileUpdatedJournalEntry(file, original, now, user);
		}
 
Example 6
Project: lams   File: HibernateTemplate.java   View source code 6 votes vote down vote up
@Override
public Object get(final String entityName, final Serializable id, final LockMode lockMode)
		throws DataAccessException {

	return executeWithNativeSession(new HibernateCallback<Object>() {
		@Override
		public Object doInHibernate(Session session) throws HibernateException {
			if (lockMode != null) {
				return session.get(entityName, id, lockMode);
			}
			else {
				return session.get(entityName, id);
			}
		}
	});
}
 
Example 7
Project: lams   File: SQLServerDialect.java   View source code 6 votes vote down vote up
@Override
public String appendLockHint(LockOptions lockOptions, String tableName) {
	final LockMode mode = lockOptions.getLockMode();
	switch ( mode ) {
		case UPGRADE:
		case UPGRADE_NOWAIT:
		case PESSIMISTIC_WRITE:
		case WRITE:
			return tableName + " with (updlock, rowlock)";
		case PESSIMISTIC_READ:
			return tableName + " with (holdlock, rowlock)";
		case UPGRADE_SKIPLOCKED:
			return tableName + " with (updlock, rowlock, readpast)";
		default:
			return tableName;
	}
}
 
Example 8
Project: ctsms   File: TrialServiceImpl.java   View source code 6 votes vote down vote up
private void checkAddEcrfFieldInput(ECRFFieldInVO ecrfFieldIn) throws ServiceException
{
	InputField field = CheckIDUtil.checkInputFieldId(ecrfFieldIn.getFieldId(), this.getInputFieldDao(), LockMode.PESSIMISTIC_WRITE);
	Trial trial = CheckIDUtil.checkTrialId(ecrfFieldIn.getTrialId(), this.getTrialDao());
	ServiceUtil.checkTrialLocked(trial);
	ECRF ecrf = CheckIDUtil.checkEcrfId(ecrfFieldIn.getEcrfId(), this.getECRFDao());
	if (!trial.equals(ecrf.getTrial())) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.ECRF_FIELD_WRONG_ECRF, CommonUtil.trialOutVOToString(this.getTrialDao().toTrialOutVO(trial)));
	}
	checkEcrfFieldInput(ecrfFieldIn);
	ServiceUtil.checkLockedEcrfs(ecrf, this.getECRFStatusEntryDao(), this.getECRFDao());
	if (ecrfFieldIn.getSeries()
			&& this.getECRFFieldDao().getCount(null, ecrfFieldIn.getEcrfId(), ecrfFieldIn.getSection(), null, null) > 0 // optimization, bulk inserts
			) {
		if (this.getECRFFieldValueDao().getCount(ecrfFieldIn.getEcrfId(), ecrfFieldIn.getSection()) > 0) {
			throw L10nUtil.initServiceException(ServiceExceptionCodes.ECRF_FIELD_SERIES_SECTION_WITH_VALUES, ecrfFieldIn.getSection());
		}
		if (this.getECRFFieldStatusEntryDao().getCount(ecrfFieldIn.getEcrfId(), ecrfFieldIn.getSection()) > 0) {
			throw L10nUtil.initServiceException(ServiceExceptionCodes.ECRF_FIELD_SERIES_SECTION_WITH_STATUS_ENTRIES, ecrfFieldIn.getSection());
		}
	}
}
 
Example 9
Project: lams   File: RDMSOS2200Dialect.java   View source code 6 votes vote down vote up
@Override
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
	// RDMS has no known variation of a "SELECT ... FOR UPDATE" syntax...
	if ( lockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT ) {
		return new PessimisticForceIncrementLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode == LockMode.PESSIMISTIC_WRITE ) {
		return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode == LockMode.PESSIMISTIC_READ ) {
		return new PessimisticReadUpdateLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode == LockMode.OPTIMISTIC ) {
		return new OptimisticLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode == LockMode.OPTIMISTIC_FORCE_INCREMENT ) {
		return new OptimisticForceIncrementLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode.greaterThan( LockMode.READ ) ) {
		return new UpdateLockingStrategy( lockable, lockMode );
	}
	else {
		return new SelectLockingStrategy( lockable, lockMode );
	}
}
 
Example 10
Project: hibernate-ogm-ignite   File: IgniteDialect.java   View source code 6 votes vote down vote up
@Override
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
	if ( lockMode == LockMode.PESSIMISTIC_FORCE_INCREMENT ) {
		return new PessimisticForceIncrementLockingStrategy( lockable, lockMode );
	}
	// else if ( lockMode==LockMode.PESSIMISTIC_WRITE ) {
	// return new PessimisticWriteLockingStrategy( lockable, lockMode );
	// }
	else if ( lockMode == LockMode.PESSIMISTIC_READ ) {
		return new IgnitePessimisticReadLockingStrategy( lockable, lockMode, provider );
	}
	else if ( lockMode == LockMode.OPTIMISTIC ) {
		return new OptimisticLockingStrategy( lockable, lockMode );
	}
	else if ( lockMode == LockMode.OPTIMISTIC_FORCE_INCREMENT ) {
		return new OptimisticForceIncrementLockingStrategy( lockable, lockMode );
	}
	else {
		return null;
	}
}
 
Example 11
Project: lams   File: Dialect.java   View source code 6 votes vote down vote up
/**
 * Get a strategy instance which knows how to acquire a database-level lock
 * of the specified mode for this dialect.
 *
 * @param lockable The persister for the entity to be locked.
 * @param lockMode The type of lock to be acquired.
 * @return The appropriate locking strategy.
 * @since 3.2
 */
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
	switch ( lockMode ) {
		case PESSIMISTIC_FORCE_INCREMENT:
			return new PessimisticForceIncrementLockingStrategy( lockable, lockMode );
		case PESSIMISTIC_WRITE:
			return new PessimisticWriteSelectLockingStrategy( lockable, lockMode );
		case PESSIMISTIC_READ:
			return new PessimisticReadSelectLockingStrategy( lockable, lockMode );
		case OPTIMISTIC:
			return new OptimisticLockingStrategy( lockable, lockMode );
		case OPTIMISTIC_FORCE_INCREMENT:
			return new OptimisticForceIncrementLockingStrategy( lockable, lockMode );
		default:
			return new SelectLockingStrategy( lockable, lockMode );
	}
}
 
Example 12
Project: ctsms   File: StaffServiceImpl.java   View source code 6 votes vote down vote up
/**
 * @see org.phoenixctms.ctsms.service.staff.StaffService#updateStaff(StaffInVO)
 */
@Override
protected StaffOutVO handleUpdateStaff(AuthenticationVO auth, StaffInVO modifiedStaff, Integer maxInstances, Integer maxParentDepth)
		throws Exception
		{
	StaffDao staffDao = this.getStaffDao();
	Staff originalStaff = CheckIDUtil.checkStaffId(modifiedStaff.getId(), staffDao, LockMode.PESSIMISTIC_WRITE);
	checkStaffInput(modifiedStaff);
	if (originalStaff.isPerson() != modifiedStaff.isPerson()) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.STAFF_PERSON_FLAG_CHANGED);
	}
	StaffOutVO original = staffDao.toStaffOutVO(originalStaff, maxInstances, maxParentDepth);
	staffDao.evict(originalStaff);
	Staff staff = staffDao.staffInVOToEntity(modifiedStaff);
	checkStaffLoop(staff);
	Timestamp now = new Timestamp(System.currentTimeMillis());
	User user = CoreUtil.getUser();
	CoreUtil.modifyVersion(originalStaff, staff, now, user);
	staffDao.update(staff);
	StaffOutVO result = staffDao.toStaffOutVO(staff, maxInstances, maxParentDepth);
	JournalEntryDao journalEntryDao = this.getJournalEntryDao();
	logSystemMessage(staff, result, now, user, SystemMessageCodes.STAFF_UPDATED, result, original, journalEntryDao);
	return result;
		}
 
Example 13
Project: ctsms   File: TrialServiceImpl.java   View source code 6 votes vote down vote up
@Override
protected ECRFStatusEntryVO handleSetEcrfStatusEntry(AuthenticationVO auth, Long ecrfId, Long probandListEntryId, Long version, Long ecrfStatusTypeId,
		Long probandListStatusTypeId)
				throws Exception {
	ProbandListEntry listEntry = CheckIDUtil.checkProbandListEntryId(probandListEntryId, this.getProbandListEntryDao(), LockMode.PESSIMISTIC_WRITE);
	ECRF ecrf = CheckIDUtil.checkEcrfId(ecrfId, this.getECRFDao(), LockMode.PESSIMISTIC_WRITE); // lock order, field updates
	ECRFStatusType statusType = CheckIDUtil.checkEcrfStatusTypeId(ecrfStatusTypeId, this.getECRFStatusTypeDao());
	Timestamp now = new Timestamp(System.currentTimeMillis());
	User user = CoreUtil.getUser();
	ECRFStatusEntry originalStatusEntry = this.getECRFStatusEntryDao().findByEcrfListEntry(ecrf.getId(), listEntry.getId());
	ECRFStatusEntryVO result;
	if (originalStatusEntry != null) {
		result = updateEcrfStatusEntry(originalStatusEntry, ecrf, listEntry, statusType, version, probandListStatusTypeId, now, user);
	} else {
		Object[] resultItems = addEcrfStatusEntry(ecrf, listEntry, statusType, probandListStatusTypeId, now, user);
		result = (ECRFStatusEntryVO) resultItems[1];
	}
	return result;
}
 
Example 14
Project: lams   File: FrontBaseDialect.java   View source code 6 votes vote down vote up
@Override
public LockingStrategy getLockingStrategy(Lockable lockable, LockMode lockMode) {
	// Frontbase has no known variation of a "SELECT ... FOR UPDATE" syntax...
	if ( lockMode==LockMode.PESSIMISTIC_FORCE_INCREMENT) {
		return new PessimisticForceIncrementLockingStrategy( lockable, lockMode);
	}
	else if ( lockMode==LockMode.PESSIMISTIC_WRITE) {
		return new PessimisticWriteUpdateLockingStrategy( lockable, lockMode);
	}
	else if ( lockMode==LockMode.PESSIMISTIC_READ) {
		return new PessimisticReadUpdateLockingStrategy( lockable, lockMode);
	}
	else if ( lockMode==LockMode.OPTIMISTIC) {
		return new OptimisticLockingStrategy( lockable, lockMode);
	}
	else if ( lockMode==LockMode.OPTIMISTIC_FORCE_INCREMENT) {
		return new OptimisticForceIncrementLockingStrategy( lockable, lockMode);
	}
	else if ( lockMode.greaterThan( LockMode.READ ) ) {
		return new UpdateLockingStrategy( lockable, lockMode );
	}
	else {
		return new SelectLockingStrategy( lockable, lockMode );
	}
}
 
Example 15
Project: ctsms   File: TrialServiceImpl.java   View source code 6 votes vote down vote up
@Override
protected TrialOutVO handleUpdateTrial(AuthenticationVO auth, TrialInVO modifiedTrial)
		throws Exception {
	TrialDao trialDao = this.getTrialDao();
	Trial originalTrial = CheckIDUtil.checkTrialId(modifiedTrial.getId(), trialDao, LockMode.PESSIMISTIC_WRITE);
	Timestamp now = new Timestamp(System.currentTimeMillis());
	User user = CoreUtil.getUser();
	checkUpdateTrialInput(originalTrial, modifiedTrial, user);
	TrialStatusType originalTrialStatusType = originalTrial.getStatus();
	TrialOutVO original = trialDao.toTrialOutVO(originalTrial);
	this.getTrialStatusTypeDao().evict(originalTrialStatusType);
	trialDao.evict(originalTrial);
	Trial trial = trialDao.trialInVOToEntity(modifiedTrial);
	// Timestamp now = new Timestamp(System.currentTimeMillis());
	// User user = CoreUtil.getUser();
	CoreUtil.modifyVersion(originalTrial, trial, now, user);
	trialDao.update(trial);
	execTrialStatusActions(originalTrialStatusType, trial, now, user);
	TrialOutVO result = trialDao.toTrialOutVO(trial);
	ServiceUtil.logSystemMessage(trial, result, now, user, SystemMessageCodes.TRIAL_UPDATED, result, original, this.getJournalEntryDao());
	return result;
}
 
Example 16
Project: lams   File: EntityEntry.java   View source code 6 votes vote down vote up
/**
 * Handle updating the internal state of the entry after actually performing
 * the database update.  Specifically we update the snapshot information and
 * escalate the lock mode
 *
 * @param entity The entity instance
 * @param updatedState The state calculated after the update (becomes the
 * new {@link #getLoadedState() loaded state}.
 * @param nextVersion The new version.
 */
public void postUpdate(Object entity, Object[] updatedState, Object nextVersion) {
	this.loadedState = updatedState;
	setLockMode( LockMode.WRITE );

	if ( getPersister().isVersioned() ) {
		this.version = nextVersion;
		getPersister().setPropertyValue( entity, getPersister().getVersionProperty(), nextVersion );
	}

	if ( getPersister().getInstrumentationMetadata().isInstrumented() ) {
		final FieldInterceptor interceptor = getPersister().getInstrumentationMetadata().extractInterceptor( entity );
		if ( interceptor != null ) {
			interceptor.clearDirty();
		}
	}

	if( entity instanceof SelfDirtinessTracker) {
		((SelfDirtinessTracker) entity).$$_hibernate_clearDirtyAttributes();
	}

	persistenceContext.getSession()
			.getFactory()
			.getCustomEntityDirtinessStrategy()
			.resetDirty( entity, getPersister(), (Session) persistenceContext.getSession() );
}
 
Example 17
Project: ctsms   File: FileServiceImpl.java   View source code 6 votes vote down vote up
/**
 * @see org.phoenixctms.ctsms.service.shared.FileService#updateFile(FileInVO)
 */
@Override
protected FileOutVO handleUpdateFile(AuthenticationVO auth, FileInVO modifiedFile)
		throws Exception
		{
	FileDao fileDao = this.getFileDao();
	File originalFile = CheckIDUtil.checkFileId(modifiedFile.getId(), fileDao, LockMode.UPGRADE_NOWAIT);
	checkFileInput(modifiedFile);
	if (!fileDao.toFileOutVO(originalFile).isDecrypted()) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_FILE);
	}
	FileOutVO original = fileDao.toFileOutVO(originalFile);
	fileDao.evict(originalFile);
	File file = fileDao.fileInVOToEntity(modifiedFile);
	Timestamp now = new Timestamp(System.currentTimeMillis());
	User user = CoreUtil.getUser();
	CoreUtil.modifyVersion(originalFile, file, now, user);
	fileDao.update(file);
	return addFileUpdatedJournalEntry(file, original, now, user);
		}
 
Example 18
Project: lams   File: Loader.java   View source code 6 votes vote down vote up
protected boolean shouldUseFollowOnLocking(
		QueryParameters parameters,
		Dialect dialect,
		List<AfterLoadAction> afterLoadActions) {
	if ( dialect.useFollowOnLocking() ) {
		// currently only one lock mode is allowed in follow-on locking
		final LockMode lockMode = determineFollowOnLockMode( parameters.getLockOptions() );
		final LockOptions lockOptions = new LockOptions( lockMode );
		if ( lockOptions.getLockMode() != LockMode.UPGRADE_SKIPLOCKED ) {
			LOG.usingFollowOnLocking();
			lockOptions.setTimeOut( parameters.getLockOptions().getTimeOut() );
			lockOptions.setScope( parameters.getLockOptions().getScope() );
			afterLoadActions.add(
					new AfterLoadAction() {
						@Override
						public void afterLoad(SessionImplementor session, Object entity, Loadable persister) {
							( (Session) session ).buildLockRequest( lockOptions ).lock( persister.getEntityName(), entity );
						}
					}
			);
			parameters.setLockOptions( new LockOptions() );
			return true;
		}
	}
	return false;
}
 
Example 19
Project: lams   File: AbstractEntityGraphVisitationStrategy.java   View source code 6 votes vote down vote up
protected FetchStrategy adjustJoinFetchIfNeeded(
		AssociationAttributeDefinition attributeDefinition, FetchStrategy fetchStrategy) {
	if ( lockMode.greaterThan( LockMode.READ ) ) {
		return new FetchStrategy( fetchStrategy.getTiming(), FetchStyle.SELECT );
	}

	final Integer maxFetchDepth = sessionFactory().getSettings().getMaximumFetchDepth();
	if ( maxFetchDepth != null && currentDepth() > maxFetchDepth ) {
		return new FetchStrategy( fetchStrategy.getTiming(), FetchStyle.SELECT );
	}

	if ( attributeDefinition.getType().isCollectionType() && isTooManyCollections() ) {
		// todo : have this revert to batch or subselect fetching once "sql gen redesign" is in place
		return new FetchStrategy( fetchStrategy.getTiming(), FetchStyle.SELECT );
	}

	return fetchStrategy;
}
 
Example 20
Project: lams   File: PessimisticWriteUpdateLockingStrategy.java   View source code 5 votes vote down vote up
/**
 * Construct a locking strategy based on SQL UPDATE statements.
 *
 * @param lockable The metadata for the entity to be locked.
 * @param lockMode Indicates the type of lock to be acquired.  Note that read-locks are not valid for this strategy.
 */
public PessimisticWriteUpdateLockingStrategy(Lockable lockable, LockMode lockMode) {
	this.lockable = lockable;
	this.lockMode = lockMode;
	if ( lockMode.lessThan( LockMode.PESSIMISTIC_READ ) ) {
		throw new HibernateException( "[" + lockMode + "] not valid for update statement" );
	}
	if ( !lockable.isVersioned() ) {
		LOG.writeLocksNotSupported( lockable.getEntityName() );
		this.sql = null;
	}
	else {
		this.sql = generateLockString();
	}
}
 
Example 21
Project: OpenDiabetes   File: HSQLDialect.java   View source code 5 votes vote down vote up
public void lock(Serializable id, Object version, Object object, SessionImplementor session)
		throws StaleObjectStateException, JDBCException {
	if ( getLockMode().greaterThan( LockMode.READ ) ) {
		log.warn( "HSQLDB supports only READ_UNCOMMITTED isolation" );
	}
	super.lock( id, version, object, session );
}
 
Example 22
Project: lemon   File: DatabaseSequenceHelper.java   View source code 5 votes vote down vote up
@Transactional
public String process(String code, Date date) {
    if (code == null) {
        throw new IllegalArgumentException("code is null");
    }

    if (date == null) {
        throw new IllegalArgumentException("date is null");
    }

    code = code.trim().toUpperCase();

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(date);
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MILLISECOND, 0);

    Date targetDate = calendar.getTime();
    String hql = "from SequenceInfo where code=?";
    Query query = sequenceInfoManager.createQuery(hql, code);
    query.setLockMode("SequenceInfo", LockMode.WRITE);

    SequenceInfo sequenceInfo = (SequenceInfo) query.setFirstResult(0)
            .setMaxResults(1).uniqueResult();

    int sequence = 0;

    if (sequenceInfo == null) {
        sequenceInfo = new SequenceInfo();
        sequenceInfo.setCode(code);
        sequenceInfo.setValue(1);
        sequenceInfo.setUpdateDate(targetDate);
    } else {
        Date updateDate = sequenceInfo.getUpdateDate();

        if (updateDate == null) {
            sequenceInfo.setUpdateDate(targetDate);
            sequenceInfo.setValue(1);
        } else if (updateDate.before(targetDate)) {
            sequenceInfo.setUpdateDate(targetDate);
            sequenceInfo.setValue(1);
        } else {
            sequenceInfo.setValue(sequenceInfo.getValue() + 1);
        }
    }

    sequenceInfoManager.save(sequenceInfo);
    sequence = sequenceInfo.getValue();

    if (sequence >= 100000) {
        throw new IllegalStateException(sequence
                + " is larger than 100000, cannot process it.");
    }

    // sequence += 100000;
    // String code = Integer.toString(sequence).substring(1);
    // return code;
    return Integer.toString(sequence);
}
 
Example 23
Project: ctsms   File: TrialServiceImpl.java   View source code 5 votes vote down vote up
private void checkUpdateInquiryInput(Inquiry originalInquiry, InquiryInVO inquiryIn) throws ServiceException
{
	InputField field = CheckIDUtil.checkInputFieldId(inquiryIn.getFieldId(), this.getInputFieldDao(), LockMode.PESSIMISTIC_WRITE);
	Trial trial = CheckIDUtil.checkTrialId(inquiryIn.getTrialId(), this.getTrialDao());
	if (!trial.equals(originalInquiry.getTrial())) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.INQUIRY_TRIAL_CHANGED);
	}
	ServiceUtil.checkTrialLocked(trial);
	checkInquiryInput(inquiryIn);
	if (!field.equals(originalInquiry.getField()) && this.getInquiryValueDao().getCount(originalInquiry.getId()) > 0) { // originalInquiry.getInquiryValues().Xsize() > 0) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.INQUIRY_INPUT_FIELD_CHANGED);
	}
}
 
Example 24
Project: ipf-flow-manager   File: FlowRepositoryImpl.java   View source code 5 votes vote down vote up
@Override
public Flow lock(Long id) {
    try {
        return getHibernateTemplate().load(Flow.class, id, LockMode.UPGRADE);
    } catch (HibernateObjectRetrievalFailureException e) {
        throw new FlowException("no flow with id " + id);
    }
}
 
Example 25
Project: lams   File: Util.java   View source code 5 votes vote down vote up
/**
 * Resolve the given result classes
 *
 * @param context The context for the resolution.  See {@link ResultSetMappingResolutionContext}
 * @param resultClasses The Classes to which the results should be mapped
 */
public static void resolveResultClasses(ResultClassesResolutionContext context, Class... resultClasses) {
	int i = 0;
	for ( Class resultClass : resultClasses ) {
		context.addQueryReturns(
				new NativeSQLQueryRootReturn( "alias" + (++i), resultClass.getName(), LockMode.READ )
		);
		try {
			final EntityPersister persister = context.getSessionFactory().getEntityPersister( resultClass.getName() );
			context.addQuerySpaces( (String[]) persister.getQuerySpaces() );
		}
		catch (Exception ignore) {
		}
	}
}
 
Example 26
Project: lams   File: HibernateTemplate.java   View source code 5 votes vote down vote up
@Override
public void lock(final String entityName, final Object entity, final LockMode lockMode)
		throws DataAccessException {

	executeWithNativeSession(new HibernateCallback<Object>() {
		@Override
		public Object doInHibernate(Session session) throws HibernateException {
			session.buildLockRequest(new LockOptions(lockMode)).lock(entityName, entity);
			return null;
		}
	});
}
 
Example 27
Project: ctsms   File: CheckIDUtil.java   View source code 5 votes vote down vote up
public static Trial checkTrialId(Long trialId, TrialDao trialDao, LockMode lockMode) throws ServiceException
{
	Trial trial = trialDao.load(trialId, lockMode);
	if (trial == null) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.INVALID_TRIAL_ID, trialId == null ? null : trialId.toString());
	}
	return trial;
}
 
Example 28
Project: ctsms   File: FileServiceImpl.java   View source code 5 votes vote down vote up
/**
 * @see org.phoenixctms.ctsms.service.shared.FileService#updateFile(FileInVO, FileStreamInVO)
 */
@Override
protected FileOutVO handleUpdateFile(AuthenticationVO auth, FileInVO modifiedFile, FileStreamInVO modifiedFileStream)
		throws Exception
		{
	FileDao fileDao = this.getFileDao();
	File originalFile = CheckIDUtil.checkFileId(modifiedFile.getId(), fileDao, LockMode.UPGRADE_NOWAIT);
	checkFileInput(modifiedFile);
	if (!fileDao.toFileOutVO(originalFile).isDecrypted()) {
		throw L10nUtil.initServiceException(ServiceExceptionCodes.CANNOT_DECRYPT_FILE);
	}
	checkFileInput(modifiedFileStream, modifiedFile.getModule());
	FileOutVO original = fileDao.toFileOutVO(originalFile);
	fileDao.evict(originalFile);
	File file = fileDao.fileInVOToEntity(modifiedFile);
	Timestamp now = new Timestamp(System.currentTimeMillis());
	User user = CoreUtil.getUser();
	CoreUtil.modifyVersion(originalFile, file, now, user);
	saveFileStream(file, modifiedFileStream);
	try {
		fileDao.update(file);
		return addFileUpdatedJournalEntry(file, original, now, user);
	} catch (Exception e) {
		try {
			dropExternalFile(true, file.getExternalFileName());
		} catch (Exception e1) {
		}
		throw e;
	}
		}
 
Example 29
Project: lams   File: NativeSQLQueryJoinReturn.java   View source code 5 votes vote down vote up
/**
 * Construct a return descriptor representing some form of fetch.
 *
 * @param alias The result alias
 * @param ownerAlias The owner's result alias
 * @param ownerProperty The owner's property representing the thing to be fetched
 * @param propertyResults Any user-supplied column->property mappings
 * @param lockMode The lock mode to apply
 */
@SuppressWarnings("unchecked")
public NativeSQLQueryJoinReturn(
		String alias,
		String ownerAlias,
		String ownerProperty,
		Map propertyResults,
		LockMode lockMode) {
	super( alias, propertyResults, lockMode );
	this.ownerAlias = ownerAlias;
	this.ownerProperty = ownerProperty;
	this.hashCode = determineHashCode();
}
 
Example 30
Project: lams   File: TwoPhaseLoad.java   View source code 5 votes vote down vote up
/**
 * Register the "hydrated" state of an entity instance, after the first step of 2-phase loading.
 *
 * Add the "hydrated state" (an array) of an uninitialized entity to the session. We don't try
 * to resolve any associations yet, because there might be other entities waiting to be
 * read from the JDBC result set we are currently processing
 *
 * @param persister The persister for the hydrated entity
 * @param id The entity identifier
 * @param values The entity values
 * @param rowId The rowId for the entity
 * @param object An optional instance for the entity being loaded
 * @param lockMode The lock mode
 * @param lazyPropertiesAreUnFetched Whether properties defined as lazy are yet un-fetched
 * @param session The Session
 */
public static void postHydrate(
		final EntityPersister persister,
		final Serializable id,
		final Object[] values,
		final Object rowId,
		final Object object,
		final LockMode lockMode,
		final boolean lazyPropertiesAreUnFetched,
		final SessionImplementor session) {
	final Object version = Versioning.getVersion( values, persister );
	session.getPersistenceContext().addEntry(
			object,
			Status.LOADING,
			values,
			rowId,
			id,
			version,
			lockMode,
			true,
			persister,
			false,
			lazyPropertiesAreUnFetched
		);

	if ( version != null && LOG.isTraceEnabled() ) {
		final String versionStr = persister.isVersioned()
				? persister.getVersionType().toLoggableString( version, session.getFactory() )
				: "null";
		LOG.tracef( "Version: %s", versionStr );
	}
}
 
Example 31
Project: ctsms   File: TrialServiceImpl.java   View source code 5 votes vote down vote up
private void checkAddProbandListEntryTagInput(ProbandListEntryTagInVO listTagIn) throws ServiceException
{
	InputField field = CheckIDUtil.checkInputFieldId(listTagIn.getFieldId(), this.getInputFieldDao(), LockMode.PESSIMISTIC_WRITE);
	Trial trial = CheckIDUtil.checkTrialId(listTagIn.getTrialId(), this.getTrialDao());
	ServiceUtil.checkTrialLocked(trial);
	checkProbandListEntryTagInput(listTagIn);
}
 
Example 32
Project: lams   File: DynamicBatchingEntityLoaderBuilder.java   View source code 5 votes vote down vote up
@Override
protected UniqueEntityLoader buildBatchingLoader(
		OuterJoinLoadable persister,
		int batchSize,
		LockMode lockMode,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers influencers) {
	return new DynamicBatchingEntityLoader( persister, batchSize, lockMode, factory, influencers );
}
 
Example 33
Project: lams   File: DynamicBatchingEntityLoaderBuilder.java   View source code 5 votes vote down vote up
public DynamicBatchingEntityLoader(
		OuterJoinLoadable persister,
		int maxBatchSize,
		LockMode lockMode,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) {
	super( persister );
	this.maxBatchSize = maxBatchSize;
	this.singleKeyLoader = new EntityLoader( persister, 1, lockMode, factory, loadQueryInfluencers );
	this.dynamicLoader = new DynamicEntityLoader( persister, maxBatchSize, lockMode, factory, loadQueryInfluencers );
}
 
Example 34
Project: ctsms   File: InventoryBookingCollisionFinder.java   View source code 5 votes vote down vote up
@Override
protected Inventory aquireWriteLock(InventoryBookingInVO in, boolean lock)
		throws ServiceException {
	if (in.getInventoryId() != null) {
		if (lock) {
			return CheckIDUtil.checkInventoryId(in.getInventoryId(), inventoryDao, LockMode.PESSIMISTIC_WRITE);
		} else {
			return CheckIDUtil.checkInventoryId(in.getInventoryId(), inventoryDao);
		}
	}
	return null;
}
 
Example 35
Project: lams   File: CollectionElementLoader.java   View source code 5 votes vote down vote up
public CollectionElementLoader(
		QueryableCollection collectionPersister,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers loadQueryInfluencers) throws MappingException {
	super( factory, loadQueryInfluencers );

	this.keyType = collectionPersister.getKeyType();
	this.indexType = collectionPersister.getIndexType();
	this.persister = (OuterJoinLoadable) collectionPersister.getElementPersister();
	this.entityName = persister.getEntityName();

	JoinWalker walker = new EntityJoinWalker(
			persister, 
			ArrayHelper.join(
					collectionPersister.getKeyColumnNames(),
					collectionPersister.toColumns("index")
			),
			1, 
			LockMode.NONE, 
			factory, 
			loadQueryInfluencers
		);
	initFromWalker( walker );

	postInstantiate();

	if ( LOG.isDebugEnabled() ) {
		LOG.debugf( "Static select for entity %s: %s", entityName, getSQLString() );
	}

}
 
Example 36
Project: lams   File: AbstractBatchingEntityLoaderBuilder.java   View source code 5 votes vote down vote up
@Override
protected UniqueEntityLoader buildNonBatchingLoader(
		OuterJoinLoadable persister,
		LockMode lockMode,
		SessionFactoryImplementor factory,
		LoadQueryInfluencers influencers) {
	return EntityLoader.forEntity( persister ).withLockMode( lockMode ).withInfluencers( influencers ).byPrimaryKey();
}
 
Example 37
Project: dev-courses   File: HSQLDialect.java   View source code 5 votes vote down vote up
public void lock(Serializable id, Object version, Object object, int timeout, SessionImplementor session)
                throws StaleObjectStateException, JDBCException {
        if ( getLockMode().greaterThan( LockMode.READ ) ) {
                log.warn( "HSQLDB supports only READ_UNCOMMITTED isolation" );
        }
        super.lock( id, version, object, timeout, session );
}
 
Example 38
Project: lams   File: AbstractEntityPersister.java   View source code 5 votes vote down vote up
protected void initLockers() {
	lockers.put( LockMode.READ, generateLocker( LockMode.READ ) );
	lockers.put( LockMode.UPGRADE, generateLocker( LockMode.UPGRADE ) );
	lockers.put( LockMode.UPGRADE_NOWAIT, generateLocker( LockMode.UPGRADE_NOWAIT ) );
	lockers.put( LockMode.UPGRADE_SKIPLOCKED, generateLocker( LockMode.UPGRADE_SKIPLOCKED ) );
	lockers.put( LockMode.FORCE, generateLocker( LockMode.FORCE ) );
	lockers.put( LockMode.PESSIMISTIC_READ, generateLocker( LockMode.PESSIMISTIC_READ ) );
	lockers.put( LockMode.PESSIMISTIC_WRITE, generateLocker( LockMode.PESSIMISTIC_WRITE ) );
	lockers.put( LockMode.PESSIMISTIC_FORCE_INCREMENT, generateLocker( LockMode.PESSIMISTIC_FORCE_INCREMENT ) );
	lockers.put( LockMode.OPTIMISTIC, generateLocker( LockMode.OPTIMISTIC ) );
	lockers.put( LockMode.OPTIMISTIC_FORCE_INCREMENT, generateLocker( LockMode.OPTIMISTIC_FORCE_INCREMENT ) );
}
 
Example 39
Project: lams   File: ResultSetProcessingContextImpl.java   View source code 5 votes vote down vote up
@Override
public LockMode resolveLockMode(EntityReference entityReference) {
	if ( queryParameters.getLockOptions() != null && queryParameters.getLockOptions()
			.getLockMode() != null ) {
		return queryParameters.getLockOptions().getLockMode();
	}
	return LockMode.READ;
}
 
Example 40
Project: lams   File: LoadEvent.java   View source code 5 votes vote down vote up
private LoadEvent(
		Serializable entityId,
		String entityClassName,
		Object instanceToLoad,
		LockOptions lockOptions,
		boolean isAssociationFetch,
		EventSource source) {

	super(source);

	if ( entityId == null ) {
		throw new IllegalArgumentException("id to load is required for loading");
	}

	if ( lockOptions.getLockMode() == LockMode.WRITE ) {
		throw new IllegalArgumentException("Invalid lock mode for loading");
	}
	else if ( lockOptions.getLockMode() == null ) {
		lockOptions.setLockMode(DEFAULT_LOCK_MODE);
	}

	this.entityId = entityId;
	this.entityClassName = entityClassName;
	this.instanceToLoad = instanceToLoad;
	this.lockOptions = lockOptions;
	this.isAssociationFetch = isAssociationFetch;
}