org.hibernate.LockMode Java Examples
The following examples show how to use
org.hibernate.LockMode.
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: CascadeLockUnidirectionalOneToManyTest.java From high-performance-java-persistence with Apache License 2.0 | 7 votes |
@Test public void testCascadeLockOnDetachedEntityUninitializedWithScope() { LOGGER.info("Test lock cascade for detached entity with scope"); //Load the Post entity, which will become detached Post post = doInJPA(entityManager -> (Post) entityManager.find(Post.class, 1L)); doInJPA(entityManager -> { LOGGER.info("Reattach and lock entity with associations not initialized"); entityManager.unwrap(Session.class) .buildLockRequest( new LockOptions(LockMode.PESSIMISTIC_WRITE)) .setScope(true) .lock(post); LOGGER.info("Check entities are reattached"); //The Post entity graph is attached containsPost(entityManager, post, true); }); }
Example #2
Source File: ProbandServiceImpl.java From ctsms with GNU Lesser General Public License v2.1 | 6 votes |
@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); 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) { 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 #3
Source File: AbstractEntityInsertAction.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Make the entity "managed" by the persistence context. */ public final void makeEntityManaged() { nullifyTransientReferencesIfNotAlready(); final Object version = Versioning.getVersion( getState(), getPersister() ); getSession().getPersistenceContext().addEntity( getInstance(), ( getPersister().isMutable() ? Status.MANAGED : Status.READ_ONLY ), getState(), getEntityKey(), version, LockMode.WRITE, isExecuted, getPersister(), isVersionIncrementDisabled ); }
Example #4
Source File: ReactiveSessionTest.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 6 votes |
@Test public void reactiveQueryWithLock(TestContext context) { final GuineaPig expectedPig = new GuineaPig( 5, "Aloi" ); test( context, populateDB() .thenCompose( v -> getSessionFactory().withTransaction( (session, tx) -> session.createQuery( "from GuineaPig pig", GuineaPig.class) .setLockMode(LockMode.PESSIMISTIC_WRITE) .getSingleResult() .thenAccept( actualPig -> { assertThatPigsAreEqual( context, expectedPig, actualPig ); context.assertEquals( session.getLockMode( actualPig ), LockMode.PESSIMISTIC_WRITE ); } ) ) ) ); }
Example #5
Source File: DefaultReactiveLoadEventListener.java From hibernate-reactive with GNU Lesser General Public License v2.1 | 6 votes |
private CompletionStage<Object> doOnLoad( final EntityPersister persister, final LoadEvent event, final LoadEventListener.LoadType loadType) { final EventSource session = event.getSession(); final EntityKey keyToLoad = session.generateEntityKey( event.getEntityId(), persister ); if ( loadType.isNakedEntityReturned() ) { //do not return a proxy! //(this option indicates we are initializing a proxy) return load( event, persister, keyToLoad, loadType ); } //return a proxy if appropriate else if ( event.getLockMode() == LockMode.NONE ) { return proxyOrLoad( event, persister, keyToLoad, loadType ); } else { return lockAndLoad( event, persister, keyToLoad, loadType, session ); } }
Example #6
Source File: ImmutableEntityEntry.java From lams with GNU General Public License v2.0 | 6 votes |
/** * Custom deserialization routine used during deserialization of a * Session/PersistenceContext for increased performance. * * @param ois The stream from which to read the entry. * @param persistenceContext The context being deserialized. * * @return The deserialized EntityEntry * * @throws java.io.IOException If a stream error occurs * @throws ClassNotFoundException If any of the classes declared in the stream * cannot be found */ public static EntityEntry deserialize( ObjectInputStream ois, PersistenceContext persistenceContext) throws IOException, ClassNotFoundException { String previousStatusString; return new ImmutableEntityEntry( persistenceContext.getSession().getFactory(), (String) ois.readObject(), (Serializable) ois.readObject(), Status.valueOf( (String) ois.readObject() ), ( previousStatusString = (String) ois.readObject() ).length() == 0 ? null : Status.valueOf( previousStatusString ), (Object[]) ois.readObject(), (Object[]) ois.readObject(), ois.readObject(), LockMode.valueOf( (String) ois.readObject() ), ois.readBoolean(), ois.readBoolean(), null ); }
Example #7
Source File: BatchingEntityLoader.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
public static UniqueEntityLoader createBatchingEntityLoader( final OuterJoinLoadable persister, final int maxBatchSize, final LockMode lockMode, final SessionFactoryImplementor factory, final Map enabledFilters) throws MappingException { if ( maxBatchSize>1 ) { int[] batchSizesToCreate = ArrayHelper.getBatchSizes(maxBatchSize); Loader[] loadersToCreate = new Loader[ batchSizesToCreate.length ]; for ( int i=0; i<batchSizesToCreate.length; i++ ) { loadersToCreate[i] = new EntityLoader(persister, batchSizesToCreate[i], lockMode, factory, enabledFilters); } return new BatchingEntityLoader(persister, batchSizesToCreate, loadersToCreate); } else { return new EntityLoader(persister, lockMode, factory, enabledFilters); } }
Example #8
Source File: QueryLoader.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
/** * @param lockModes a collection of lock modes specified dynamically via the Query interface */ protected LockMode[] getLockModes(Map lockModes) { if ( lockModes==null || lockModes.size()==0 ) { return defaultLockModes; } else { // unfortunately this stuff can't be cached because // it is per-invocation, not constant for the // QueryTranslator instance LockMode[] lockModeArray = new LockMode[entityAliases.length]; for ( int i = 0; i < entityAliases.length; i++ ) { LockMode lockMode = (LockMode) lockModes.get( entityAliases[i] ); if ( lockMode == null ) { //NONE, because its the requested lock mode, not the actual! lockMode = LockMode.NONE; } lockModeArray[i] = lockMode; } return lockModeArray; } }
Example #9
Source File: FollowOnLockingTest.java From high-performance-java-persistence with Apache License 2.0 | 6 votes |
@Test public void testUpgradeSkipLockedOrderBy() { LOGGER.info("Test lock contention"); doInJPA(entityManager -> { List<Post> pendingPosts = entityManager.createQuery( "select p " + "from Post p " + "where p.status = :status " + "order by p.id ", Post.class) .setParameter("status", PostStatus.PENDING) .setFirstResult(2) .unwrap(org.hibernate.Query.class) .setLockOptions(new LockOptions(LockMode.UPGRADE_SKIPLOCKED)) .list(); assertEquals(3, pendingPosts.size()); }); }
Example #10
Source File: TwoPhaseLoad.java From cacheonix-core with GNU Lesser General Public License v2.1 | 6 votes |
public static void addUninitializedCachedEntity( final EntityKey key, final Object object, final EntityPersister persister, final LockMode lockMode, final boolean lazyPropertiesAreUnfetched, final Object version, final SessionImplementor session ) { session.getPersistenceContext().addEntity( object, Status.LOADING, null, key, version, lockMode, true, persister, false, lazyPropertiesAreUnfetched ); }
Example #11
Source File: HibernateTemplate.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Override public <T> T load(final Class<T> entityClass, final Serializable id, final LockMode lockMode) throws DataAccessException { return executeWithNativeSession(new HibernateCallback<T>() { @Override @SuppressWarnings("unchecked") public T doInHibernate(Session session) throws HibernateException { if (lockMode != null) { return (T) session.load(entityClass, id, lockMode); } else { return (T) session.load(entityClass, id); } } }); }
Example #12
Source File: JobCollisionFinder.java From ctsms with GNU Lesser General Public License v2.1 | 6 votes |
@Override protected ROOT aquireWriteLock(JobAddVO in) throws ServiceException { switch (module) { case TRIAL_JOB: return (ROOT) trialDao.load(in.getTrialId(), LockMode.PESSIMISTIC_WRITE); case PROBAND_JOB: return (ROOT) probandDao.load(in.getProbandId(), LockMode.PESSIMISTIC_WRITE); case INPUT_FIELD_JOB: return (ROOT) inputFieldDao.load(in.getInputFieldId(), LockMode.PESSIMISTIC_WRITE); case INVENTORY_CRITERIA_JOB: case STAFF_CRITERIA_JOB: case COURSE_CRITERIA_JOB: case TRIAL_CRITERIA_JOB: case INPUT_FIELD_CRITERIA_JOB: case PROBAND_CRITERIA_JOB: case USER_CRITERIA_JOB: case MASS_MAIL_CRITERIA_JOB: return (ROOT) criteriaDao.load(in.getCriteriaId(), LockMode.PESSIMISTIC_WRITE); default: // not supported for now... throw new IllegalArgumentException(L10nUtil.getMessage(MessageCodes.UNSUPPORTED_JOB_MODULE, DefaultMessages.UNSUPPORTED_JOB_MODULE, new Object[] { module.toString() })); } }
Example #13
Source File: FileServiceImpl.java From ctsms with GNU Lesser General Public License v2.1 | 6 votes |
/** * @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 #14
Source File: HibernateTemplate.java From lams with GNU General Public License v2.0 | 6 votes |
@Override public <T> T load(final Class<T> entityClass, final Serializable id, final LockMode lockMode) throws DataAccessException { return executeWithNativeSession(new HibernateCallback<T>() { @Override @SuppressWarnings("unchecked") public T doInHibernate(Session session) throws HibernateException { if (lockMode != null) { return (T) session.load(entityClass, id, lockMode); } else { return (T) session.load(entityClass, id); } } }); }
Example #15
Source File: Main.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Demonstrates transitive persistence with detached object support */ public void bidOnAuction(User bidder, AuctionItem item, float amount) throws Exception { System.out.println("Creating a new bid for auction item: " + item.getId() + " by user: " + bidder.getId() ); Session s = factory.openSession(); Transaction tx=null; try { tx = s.beginTransaction(); s.lock(item, LockMode.NONE); s.lock(bidder, LockMode.NONE); Bid bid = new Bid(); bid.setBidder(bidder); bid.setDatetime( new Date() ); bid.setAmount(amount); bid.setItem(item); bidder.getBids().add(bid); item.getBids().add(bid); tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); throw e; } finally { s.close(); } }
Example #16
Source File: HibernateTemplate.java From lams with GNU General Public License v2.0 | 5 votes |
@Override public void update(final Object entity, final LockMode lockMode) throws DataAccessException { executeWithNativeSession(new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException { checkWriteOperationAllowed(session); session.update(entity); if (lockMode != null) { session.buildLockRequest(new LockOptions(lockMode)).lock(entity); } return null; } }); }
Example #17
Source File: BaseDao.java From projectforge-webapp with GNU General Public License v3.0 | 5 votes |
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS) public O internalGetById(final Serializable id) { if (id == null) { return null; } final O obj = getHibernateTemplate().get(clazz, id, LockMode.READ); afterLoad(obj); return obj; }
Example #18
Source File: HibernateTemplate.java From spring-analysis-note with MIT License | 5 votes |
@Override public void lock(final Object entity, final LockMode lockMode) throws DataAccessException { executeWithNativeSession(session -> { session.buildLockRequest(new LockOptions(lockMode)).lock(entity); return null; }); }
Example #19
Source File: UserServiceImpl.java From ctsms with GNU Lesser General Public License v2.1 | 5 votes |
@Override protected UserOutVO handleUpdateUser(AuthenticationVO auth, UserInVO modifiedUser, String plainNewDepartmentPassword, String plainOldDepartmentPassword, Integer maxInstances) throws Exception { UserDao userDao = this.getUserDao(); User originalUser = CheckIDUtil.checkUserId(modifiedUser.getId(), userDao, LockMode.PESSIMISTIC_WRITE); if (plainNewDepartmentPassword == null) { plainNewDepartmentPassword = getPlainDepartmentPassword(); } if (plainOldDepartmentPassword == null) { plainOldDepartmentPassword = getPlainDepartmentPassword(); } ServiceUtil.checkUserInput(modifiedUser, originalUser, plainNewDepartmentPassword, this.getDepartmentDao(), this.getStaffDao()); boolean departmentChanged = !originalUser.getDepartment().getId().equals(modifiedUser.getDepartmentId()); if (departmentChanged) { if (!CryptoUtil.checkDepartmentPassword(originalUser.getDepartment(), plainOldDepartmentPassword)) { throw L10nUtil.initServiceException(ServiceExceptionCodes.OLD_DEPARTMENT_PASSWORD_WRONG); } } UserOutVO original = userDao.toUserOutVO(originalUser, maxInstances); userDao.evict(originalUser); User user = userDao.userInVOToEntity(modifiedUser); if (departmentChanged) { ServiceUtil.updateUserDepartmentPassword(user, plainNewDepartmentPassword, plainOldDepartmentPassword, this.getKeyPairDao(), this.getPasswordDao()); } Timestamp now = new Timestamp(System.currentTimeMillis()); User modified = CoreUtil.getUser(); CoreUtil.modifyVersion(originalUser, user, now, modified); userDao.update(user); notifyUserAccount(user, originalUser, now); UserOutVO result = userDao.toUserOutVO(user, maxInstances); JournalEntryDao journalEntryDao = this.getJournalEntryDao(); logSystemMessage(user, result, now, modified, SystemMessageCodes.USER_UPDATED, result, original, journalEntryDao); Staff identity = user.getIdentity(); if (identity != null) { logSystemMessage(identity, result, now, modified, SystemMessageCodes.USER_UPDATED, result, original, journalEntryDao); } return result; }
Example #20
Source File: HibernateTemplate.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void delete(final Object entity, final LockMode lockMode) throws DataAccessException { executeWithNativeSession(new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException { checkWriteOperationAllowed(session); if (lockMode != null) { session.buildLockRequest(new LockOptions(lockMode)).lock(entity); } session.delete(entity); return null; } }); }
Example #21
Source File: LoadEvent.java From lams with GNU General Public License v2.0 | 5 votes |
private LoadEvent( Serializable entityId, String entityClassName, Object instanceToLoad, LockMode lockMode, boolean isAssociationFetch, EventSource source) { this( entityId, entityClassName, instanceToLoad, lockMode == DEFAULT_LOCK_MODE ? DEFAULT_LOCK_OPTIONS : new LockOptions().setLockMode( lockMode ), isAssociationFetch, source ); }
Example #22
Source File: CascadeLockUnidirectionalOneToManyTest.java From high-performance-java-persistence with Apache License 2.0 | 5 votes |
@Test public void testCascadeLockOnDetachedEntityWithoutScope() { LOGGER.info("Test lock cascade for detached entity without scope"); //Load the Post entity, which will become detached Post post = doInJPA(entityManager -> (Post) entityManager.createQuery( "select p " + "from Post p " + "join fetch p.details " + "join fetch p.comments " + "where p.id = :id" ).setParameter("id", 1L) .getSingleResult()); //Change the detached entity state post.setTitle("Hibernate Training"); doInJPA(entityManager -> { Session session = entityManager.unwrap(Session.class); //The Post entity graph is detached containsPost(entityManager, post, false); //The Lock request associates the entity graph and locks the requested entity session.buildLockRequest(new LockOptions(LockMode.PESSIMISTIC_WRITE)).lock(post); //Hibernate doesn't know if the entity is dirty assertEquals("Hibernate Training", post.getTitle()); //The Post entity graph is attached containsPost(entityManager, post, true); }); doInJPA(entityManager -> { //The detached Post entity changes have been lost Post _post = (Post) entityManager.find(Post.class, 1L); assertEquals("Hibernate Master Class", _post.getTitle()); }); }
Example #23
Source File: DefaultReplicateEventListener.java From lams with GNU General Public License v2.0 | 5 votes |
private void performReplication( Object entity, Serializable id, Object version, EntityPersister persister, ReplicationMode replicationMode, EventSource source) throws HibernateException { if ( LOG.isTraceEnabled() ) { LOG.tracev( "Replicating changes to {0}", MessageHelper.infoString( persister, id, source.getFactory() ) ); } new OnReplicateVisitor( source, id, entity, true ).process( entity, persister ); source.getPersistenceContext().addEntity( entity, ( persister.isMutable() ? Status.MANAGED : Status.READ_ONLY ), null, source.generateEntityKey( id, persister ), version, LockMode.NONE, true, persister, true ); cascadeAfterReplicate( entity, persister, replicationMode, source ); }
Example #24
Source File: HSQLDialect.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
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 #25
Source File: RefreshEvent.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
public RefreshEvent(Object object, LockMode lockMode, EventSource source) { this(object, source); if (lockMode == null) { throw new IllegalArgumentException("Attempt to generate refresh event with null lock mode"); } this.lockMode = lockMode; }
Example #26
Source File: HibernateTemplate.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Override public void refresh(final Object entity, final LockMode lockMode) throws DataAccessException { executeWithNativeSession(new HibernateCallback<Object>() { @Override public Object doInHibernate(Session session) throws HibernateException { if (lockMode != null) { session.refresh(entity, new LockOptions(lockMode)); } else { session.refresh(entity); } return null; } }); }
Example #27
Source File: OneToManyJoinWalker.java From lams with GNU General Public License v2.0 | 5 votes |
public OneToManyJoinWalker( QueryableCollection oneToManyPersister, int batchSize, String subquery, SessionFactoryImplementor factory, LoadQueryInfluencers loadQueryInfluencers) throws MappingException { super( factory, loadQueryInfluencers ); this.oneToManyPersister = oneToManyPersister; final OuterJoinLoadable elementPersister = (OuterJoinLoadable) oneToManyPersister.getElementPersister(); final String alias = generateRootAlias( oneToManyPersister.getRole() ); walkEntityTree( elementPersister, alias ); List allAssociations = new ArrayList(); allAssociations.addAll( associations ); allAssociations.add( OuterJoinableAssociation.createRoot( oneToManyPersister.getCollectionType(), alias, getFactory() ) ); initPersisters( allAssociations, LockMode.NONE ); initStatementString( elementPersister, alias, batchSize, subquery ); }
Example #28
Source File: Dialect.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Given a lock mode, determine the appropriate for update fragment to use. * * @param lockMode The lock mode to apply. * @return The appropriate for update fragment. */ public String getForUpdateString(LockMode lockMode) { if ( lockMode==LockMode.UPGRADE ) { return getForUpdateString(); } else if ( lockMode==LockMode.UPGRADE_NOWAIT ) { return getForUpdateNowaitString(); } else if ( lockMode==LockMode.FORCE ) { return getForUpdateNowaitString(); } else { return ""; } }
Example #29
Source File: CheckIDUtil.java From ctsms with GNU Lesser General Public License v2.1 | 5 votes |
public static File checkFileId(Long fileId, FileDao fileDao, LockMode lockMode) throws ServiceException { File file = fileDao.load(fileId, lockMode); if (file == null) { throw L10nUtil.initServiceException(ServiceExceptionCodes.INVALID_FILE_ID, fileId == null ? null : fileId.toString()); } return file; }
Example #30
Source File: UnionSubclassEntityPersister.java From cacheonix-core with GNU Lesser General Public License v2.1 | 5 votes |
/** * Generate the SQL that selects a row by id */ protected String generateSelectString(LockMode lockMode) { SimpleSelect select = new SimpleSelect( getFactory().getDialect() ) .setLockMode(lockMode) .setTableName( getTableName() ) .addColumns( getIdentifierColumnNames() ) .addColumns( getSubclassColumnClosure(), getSubclassColumnAliasClosure(), getSubclassColumnLazyiness() ) .addColumns( getSubclassFormulaClosure(), getSubclassFormulaAliasClosure(), getSubclassFormulaLazyiness() ); //TODO: include the rowids!!!! if ( hasSubclasses() ) { if ( isDiscriminatorFormula() ) { select.addColumn( getDiscriminatorFormula(), getDiscriminatorAlias() ); } else { select.addColumn( getDiscriminatorColumnName(), getDiscriminatorAlias() ); } } if ( getFactory().getSettings().isCommentsEnabled() ) { select.setComment( "load " + getEntityName() ); } return select.addCondition( getIdentifierColumnNames(), "=?" ).toStatementString(); }