List of usage examples for org.hibernate LockMode PESSIMISTIC_WRITE
LockMode PESSIMISTIC_WRITE
To view the source code for org.hibernate LockMode PESSIMISTIC_WRITE.
Click Source Link
From source file:org.projectforge.framework.persistence.api.BaseDao.java
License:Open Source License
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ) public void internalMarkAsDeleted(final O obj) { if (HistoryBaseDaoAdapter.isHistorizable(obj) == false) { log.error(/*from w w w. ja v a 2 s. com*/ "Object is not historizable. Therefore marking as deleted is not supported. Please use delete instead."); throw new InternalErrorException(); } onDelete(obj); final O dbObj = hibernateTemplate.load(clazz, obj.getId(), LockMode.PESSIMISTIC_WRITE); onSaveOrModify(obj); BaseDaoJpaAdapter.beforeUpdateCopyMarkDelete(dbObj, obj); copyValues(obj, dbObj, "deleted"); // If user has made additional changes. dbObj.setDeleted(true); dbObj.setLastUpdate(); flushSession(); flushSearchSession(); afterSaveOrModify(obj); afterDelete(obj); flushSession(); log.info("Object marked as deleted: " + dbObj.toString()); }
From source file:org.projectforge.framework.persistence.api.BaseDao.java
License:Open Source License
/** * Object will be deleted finally out of the data base. * * @param obj/*from ww w .j a v a 2s . c om*/ */ @Override @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ) public void delete(final O obj) throws AccessException { Validate.notNull(obj); if (HistoryBaseDaoAdapter.isHistorizable(obj) == true) { final String msg = EXCEPTION_HISTORIZABLE_NOTDELETABLE + obj.toString(); log.error(msg); throw new RuntimeException(msg); } if (obj.getId() == null) { final String msg = "Could not destroy object unless id is not given: " + obj.toString(); log.error(msg); throw new RuntimeException(msg); } accessChecker.checkRestrictedOrDemoUser(); onDelete(obj); final O dbObj = hibernateTemplate.load(clazz, obj.getId(), LockMode.PESSIMISTIC_WRITE); checkPartOfCurrentTenant(obj, OperationType.DELETE); checkLoggedInUserDeleteAccess(obj, dbObj); hibernateTemplate.delete(dbObj); log.info("Object deleted: " + obj.toString()); afterSaveOrModify(obj); afterDelete(obj); }
From source file:org.projectforge.framework.persistence.api.BaseDao.java
License:Open Source License
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ) public void internalUndelete(final O obj) { final O dbObj = hibernateTemplate.load(clazz, obj.getId(), LockMode.PESSIMISTIC_WRITE); onSaveOrModify(obj);/*from w w w . j a v a 2 s.c o m*/ BaseDaoJpaAdapter.beforeUpdateCopyMarkUnDelete(dbObj, obj); copyValues(obj, dbObj, "deleted"); // If user has made additional changes. dbObj.setDeleted(false); obj.setDeleted(false); dbObj.setLastUpdate(); obj.setLastUpdate(dbObj.getLastUpdate()); log.info("Object undeleted: " + dbObj.toString()); flushSession(); flushSearchSession(); afterSaveOrModify(obj); afterUndelete(obj); }
From source file:org.projectforge.plugins.crm.PersonalContactDao.java
License:Open Source License
/** * @param obj/* ww w. j a va 2 s .c o m*/ * @return true, if already existing entry was updated, otherwise false (e. g. if no entry exists for update). */ private boolean internalUpdate(final PersonalContactDO obj) { PersonalContactDO dbObj = null; if (obj.getId() != null) { dbObj = hibernateTemplate.load(PersonalContactDO.class, obj.getId(), LockMode.PESSIMISTIC_WRITE); } if (dbObj == null) { dbObj = getByContactId(obj.getContactId()); } if (dbObj == null) { return false; } checkAccess(dbObj); Validate.isTrue(ObjectUtils.equals(dbObj.getContactId(), obj.getContactId())); obj.setId(dbObj.getId()); // Copy all values of modified user to database object. final ModificationStatus modified = dbObj.copyValuesFrom(obj, "owner", "address", "id"); if (modified == ModificationStatus.MAJOR) { dbObj.setLastUpdate(); log.info("Object updated: " + dbObj.toString()); } return true; }
From source file:org.projectforge.user.GroupDao.java
License:Open Source License
/** * Assigns groups to and unassigns groups from given user. * @param user// w w w . j a va 2 s . c o m * @param groupsToAssign Groups to assign (nullable). * @param groupsToUnassign Groups to unassign (nullable). * @throws AccessException */ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ) public void assignGroups(final PFUserDO user, final Set<GroupDO> groupsToAssign, final Set<GroupDO> groupsToUnassign) throws AccessException { getHibernateTemplate().refresh(user, LockMode.READ); final List<GroupDO> assignedGroups = new ArrayList<GroupDO>(); if (groupsToAssign != null) { for (final GroupDO group : groupsToAssign) { final GroupDO dbGroup = getHibernateTemplate().get(clazz, group.getId(), LockMode.PESSIMISTIC_WRITE); Set<PFUserDO> assignedUsers = dbGroup.getAssignedUsers(); if (assignedUsers == null) { assignedUsers = new HashSet<PFUserDO>(); dbGroup.setAssignedUsers(assignedUsers); } if (assignedUsers.contains(user) == false) { log.info("Assigning user '" + user.getUsername() + "' to group '" + dbGroup.getName() + "'."); assignedUsers.add(user); assignedGroups.add(dbGroup); dbGroup.setLastUpdate(); // Needed, otherwise GroupDO is not detected for hibernate history! } else { log.info("User '" + user.getUsername() + "' already assigned to group '" + dbGroup.getName() + "'."); } } } final List<GroupDO> unassignedGroups = new ArrayList<GroupDO>(); if (groupsToUnassign != null) { for (final GroupDO group : groupsToUnassign) { final GroupDO dbGroup = getHibernateTemplate().get(clazz, group.getId(), LockMode.PESSIMISTIC_WRITE); final Set<PFUserDO> assignedUsers = dbGroup.getAssignedUsers(); if (assignedUsers != null && assignedUsers.contains(user) == true) { log.info("Unassigning user '" + user.getUsername() + "' from group '" + dbGroup.getName() + "'."); assignedUsers.remove(user); unassignedGroups.add(dbGroup); dbGroup.setLastUpdate(); // Needed, otherwise GroupDO is not detected for hibernate history! } else { log.info("User '" + user.getUsername() + "' is not assigned to group '" + dbGroup.getName() + "' (can't unassign)."); } } } getSession().flush(); createHistoryEntry(user, unassignedGroups, assignedGroups); userGroupCache.setExpired(); }
From source file:org.projectforge.user.UserDao.java
License:Open Source License
/** * User can modify own setting, this method ensures that only such properties will be updated, the user's are allowed to. * @param user// w ww .ja va2s . c o m */ @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ) public void updateMyAccount(final PFUserDO user) { accessChecker.checkRestrictedOrDemoUser(); final PFUserDO contextUser = PFUserContext.getUser(); Validate.isTrue(user.getId().equals(contextUser.getId()) == true); final PFUserDO dbUser = getHibernateTemplate().load(clazz, user.getId(), LockMode.PESSIMISTIC_WRITE); if (copyValues(user, dbUser, "deleted", "password", "lastLogin", "loginFailures", "username", "stayLoggedInKey", "authenticationToken", "rights") != ModificationStatus.NONE) { dbUser.setLastUpdate(); log.info("Object updated: " + dbUser.toString()); copyValues(user, contextUser, "deleted", "password", "lastLogin", "loginFailures", "username", "stayLoggedInKey", "authenticationToken", "rights"); } else { log.info("No modifications detected (no update needed): " + dbUser.toString()); } userGroupCache.updateUser(user); }
From source file:org.sakaiproject.assignment.impl.persistence.AssignmentRepositoryImpl.java
License:Educational Community License
@Override @Transactional/*from w ww . ja v a2 s .c o m*/ public AssignmentSubmission newSubmission(String assignmentId, Optional<String> groupId, Optional<Set<AssignmentSubmissionSubmitter>> submitters, Optional<Set<String>> feedbackAttachments, Optional<Set<String>> submittedAttachments, Optional<Map<String, String>> properties) { Assignment assignment = findAssignment(assignmentId); if (assignment != null) { Session session = sessionFactory.getCurrentSession(); // Since this transaction is going to add a submission to the assignment we lock the assignment // the lock is freed once transaction is committed or rolled back session.buildLockRequest(LockOptions.UPGRADE).setLockMode(LockMode.PESSIMISTIC_WRITE).lock(assignment); AssignmentSubmission submission = new AssignmentSubmission(); submission.setDateCreated(Instant.now()); submitters.ifPresent(submission::setSubmitters); submitters.ifPresent(s -> s.forEach(submitter -> submitter.setSubmission(submission))); feedbackAttachments.ifPresent(submission::setFeedbackAttachments); submittedAttachments.ifPresent(submission::setAttachments); properties.ifPresent(submission::setProperties); if (assignment.getIsGroup()) { groupId.ifPresent(submission::setGroupId); } submission.setAssignment(assignment); assignment.getSubmissions().add(submission); session.persist(assignment); return submission; } return null; }
From source file:org.vpac.ndg.storage.dao.TimeSliceLockDaoImpl.java
License:Open Source License
@Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED) TimeSliceLock tryReadLock(String timeSliceId, String processId, String operation, String user) throws IllegalMonitorStateException { // First lock the timeslice row. Set scope to prevent cascading. TimeSlice ts = (TimeSlice) getSession().load(TimeSlice.class, timeSliceId, new LockOptions(LockMode.PESSIMISTIC_WRITE)); // Check status. Can't lock if there is a write lock, but can if there // are read locks. if (ts.getLockCount() > 0 && ts.getLockMode() == 'w') { // Throw unchecked exception to force rollback. // http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html#transaction-declarative-rolling-back log.debug("{} is write-locked", ts); throw new IllegalMonitorStateException("Already locked."); }/* w ww .j a v a 2 s. c om*/ log.trace("Incrementing read lock for {}; was {}", ts.getLockCount()); ts.setLockCount(ts.getLockCount() + 1); ts.setLockMode('r'); getSession().saveOrUpdate(ts); // Now that the lock has been obtained, create some metadata to allow // others to trace the lock. This is very important: without this, it's // impossible to distinguish between a valid lock and one that belonged // to a machine that has crashed. TimeSliceLock tslock = new TimeSliceLock(); tslock.setTimesliceId(ts.getId()); tslock.setProcessId(processId); tslock.setOperation(operation); tslock.setUser(user); tslock.setState(RunningTaskState.RUNNING); create(tslock); return tslock; }
From source file:org.vpac.ndg.storage.dao.TimeSliceLockDaoImpl.java
License:Open Source License
@Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED) TimeSliceLock tryWriteLock(String timeSliceId, String processId, String operation, String user) throws IllegalMonitorStateException { // First lock the timeslice row. Set scope to prevent cascading. TimeSlice ts = (TimeSlice) getSession().load(TimeSlice.class, timeSliceId, new LockOptions(LockMode.PESSIMISTIC_WRITE)); // Check status. We can't lock if there are *any* other locks held - // read or write. if (ts.getLockCount() > 0) { // Throw unchecked exception to force rollback. // http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html#transaction-declarative-rolling-back log.debug("{} is already locked (count: {})", ts, ts.getLockCount()); throw new IllegalMonitorStateException("Already locked."); }//from w w w . j a v a 2 s . c o m log.trace("Incrementing write lock for {}; was {}", ts.getLockCount()); ts.setLockCount(ts.getLockCount() + 1); ts.setLockMode('w'); getSession().saveOrUpdate(ts); // Now that the lock has been obtained, create some metadata to allow // others to trace the lock. This is very important: without this, it's // impossible to distinguish between a valid lock and one that belonged // to a machine that has crashed. TimeSliceLock tslock = new TimeSliceLock(); tslock.setTimesliceId(ts.getId()); tslock.setProcessId(processId); tslock.setOperation(operation); tslock.setUser(user); tslock.setState(RunningTaskState.RUNNING); create(tslock); return tslock; }
From source file:org.vpac.ndg.storage.dao.TimeSliceLockDaoImpl.java
License:Open Source License
@Override @Transactional(readOnly = false, isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED) public void unlock(TimeSliceLock lock) { // First lock the timeslice row. Set scope to prevent cascading. TimeSlice ts = (TimeSlice) getSession().load(TimeSlice.class, lock.getTimesliceId(), new LockOptions(LockMode.PESSIMISTIC_WRITE)); // Check status. if (ts.getLockCount() <= 0) { throw new IllegalMonitorStateException(String.format("Time slice %s is not locked.", ts)); }//w ww . java 2 s .c o m log.trace("Decrementing read lock for {}", ts); ts.setLockCount(ts.getLockCount() - 1); getSession().saveOrUpdate(ts); delete(lock); }