Example usage for org.hibernate LockMode PESSIMISTIC_WRITE

List of usage examples for org.hibernate LockMode PESSIMISTIC_WRITE

Introduction

In this page you can find the example usage for org.hibernate LockMode PESSIMISTIC_WRITE.

Prototype

LockMode PESSIMISTIC_WRITE

To view the source code for org.hibernate LockMode PESSIMISTIC_WRITE.

Click Source Link

Document

Transaction will obtain a database lock immediately.

Usage

From source file:org.projectforge.business.multitenancy.TenantDao.java

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ)
public void internalAssignTenants(final PFUserDO user, final Set<TenantDO> tenantsToAssign,
        final Set<TenantDO> tenantsToUnassign, boolean checkAccess, boolean createHistoryEntry)
        throws AccessException {
    getHibernateTemplate().refresh(user, LockMode.READ);
    if (checkAccess) {
        if (TenantChecker.isSuperAdmin(ThreadLocalUserContext.getUser()) == false) {
            log.warn("User has now access right to change assigned users of a tenant! Skipping assignment.");
            return;
        }//from w  ww  .  jav a 2s  .c  o  m
    }
    final List<TenantDO> assignedTenants = new ArrayList<TenantDO>();
    if (tenantsToAssign != null) {
        for (final TenantDO tenant : tenantsToAssign) {
            final TenantDO dbTenant = getHibernateTemplate().get(clazz, tenant.getId(),
                    LockMode.PESSIMISTIC_WRITE);
            Set<PFUserDO> assignedUsers = dbTenant.getAssignedUsers();
            if (assignedUsers == null) {
                assignedUsers = new HashSet<PFUserDO>();
                dbTenant.setAssignedUsers(assignedUsers);
            }
            if (assignedUsers.contains(user) == false) {
                log.info("Assigning user '" + user.getUsername() + "' to tenant '" + dbTenant.getName() + "'.");
                assignedUsers.add(user);
                assignedTenants.add(dbTenant);
                dbTenant.setLastUpdate(); // Needed, otherwise TenantDO is not detected for hibernate history!
            } else {
                log.info("User '" + user.getUsername() + "' already assigned to tenant '" + dbTenant.getName()
                        + "'.");
            }
        }
    }
    final List<TenantDO> unassignedTenants = new ArrayList<TenantDO>();
    if (tenantsToUnassign != null) {
        for (final TenantDO tenant : tenantsToUnassign) {
            final TenantDO dbTenant = getHibernateTemplate().get(clazz, tenant.getId(),
                    LockMode.PESSIMISTIC_WRITE);
            final Set<PFUserDO> assignedUsers = dbTenant.getAssignedUsers();
            if (assignedUsers != null && assignedUsers.contains(user) == true) {
                log.info("Unassigning user '" + user.getUsername() + "' from tenant '" + dbTenant.getName()
                        + "'.");
                assignedUsers.remove(user);
                unassignedTenants.add(dbTenant);
                dbTenant.setLastUpdate(); // Needed, otherwise TenantDO is not detected for hibernate history!
            } else {
                log.info("User '" + user.getUsername() + "' is not assigned to tenant '" + dbTenant.getName()
                        + "' (can't unassign).");
            }
        }
    }
    flushSession();
    if (createHistoryEntry) {
        createHistoryEntry(user, unassignedTenants, assignedTenants);
    }
}

From source file:org.projectforge.business.user.GroupDao.java

License:Open Source License

/**
 * Assigns groups to and unassigns groups from given user.
 *
 * @param user// w  w w  . j  a  v  a  2s  .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, final boolean updateUserGroupCache) {
    getHibernateTemplate().refresh(user, LockMode.READ);

    final List<GroupDO> assignedGroups = new ArrayList<>();
    if (groupsToAssign != null) {
        for (final GroupDO group : groupsToAssign) {
            final GroupDO dbGroup = getHibernateTemplate().get(clazz, group.getId(),
                    LockMode.PESSIMISTIC_WRITE);
            HistoryBaseDaoAdapter.wrappHistoryUpdate(dbGroup, () -> {
                Set<PFUserDO> assignedUsers = dbGroup.getAssignedUsers();
                if (assignedUsers == null) {
                    assignedUsers = new HashSet<>();
                    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()
                            + "'.");
                }
                return null;
            });
        }
    }

    final List<GroupDO> unassignedGroups = new ArrayList<>();
    if (groupsToUnassign != null) {
        for (final GroupDO group : groupsToUnassign) {
            final GroupDO dbGroup = getHibernateTemplate().get(clazz, group.getId(),
                    LockMode.PESSIMISTIC_WRITE);
            HistoryBaseDaoAdapter.wrappHistoryUpdate(dbGroup, () -> {
                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).");
                }
                return null;
            });
        }
    }

    flushSession();
    createHistoryEntry(user, unassignedGroups, assignedGroups);
    if (updateUserGroupCache) {
        getUserGroupCache().setExpired();
    }
}

From source file:org.projectforge.business.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.//  w ww  .  j  av a 2s .  co  m
 * 
 * @param user
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ)
public void updateMyAccount(final PFUserDO user) {
    accessChecker.checkRestrictedOrDemoUser();
    final PFUserDO contextUser = ThreadLocalUserContext.getUser();
    Validate.isTrue(user.getId().equals(contextUser.getId()) == true);
    final PFUserDO dbUser = getHibernateTemplate().load(clazz, user.getId(), LockMode.PESSIMISTIC_WRITE);
    final String[] ignoreFields = { "deleted", "password", "lastLogin", "loginFailures", "username",
            "stayLoggedInKey", "authenticationToken", "rights" };
    final ModificationStatus result = HistoryBaseDaoAdapter.wrappHistoryUpdate(dbUser,
            () -> copyValues(user, dbUser, ignoreFields));
    if (result != ModificationStatus.NONE) {
        dbUser.setLastUpdate();
        log.info("Object updated: " + dbUser.toString());
        copyValues(user, contextUser, ignoreFields);
    } else {
        log.info("No modifications detected (no update needed): " + dbUser.toString());
    }
    getUserGroupCache().updateUser(user);
}

From source file:org.projectforge.core.BaseDao.java

License:Open Source License

/**
 * This method is for internal use e. g. for updating objects without check access.<br/>
 * Please note: update ignores the field deleted. Use markAsDeleted, delete and undelete methods instead.
 * @param obj/*from   w  w  w.j  a v a  2  s  . co  m*/
 * @param checkAccess If false, any access check will be ignored.
 * @return true, if modifications were done, false if no modification detected.
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
public ModificationStatus internalUpdate(final O obj, final boolean checkAccess) {
    onSaveOrModify(obj);
    if (checkAccess == true) {
        accessChecker.checkRestrictedOrDemoUser();
    }
    final O dbObj = getHibernateTemplate().load(clazz, obj.getId(), LockMode.PESSIMISTIC_WRITE);
    if (checkAccess == true) {
        checkLoggedInUserUpdateAccess(obj, dbObj);
    }
    onChange(obj, dbObj);
    final O dbObjBackup;
    if (supportAfterUpdate == true) {
        dbObjBackup = getBackupObject(dbObj);
    } else {
        dbObjBackup = null;
    }
    final boolean wantsReindexAllDependentObjects = wantsReindexAllDependentObjects(obj, dbObj);
    // Copy all values of modified user to database object, ignore field 'deleted'.
    final ModificationStatus result = copyValues(obj, dbObj, "deleted");
    if (result != ModificationStatus.NONE) {
        dbObj.setLastUpdate();
        log.info("Object updated: " + dbObj.toString());
    } else {
        log.info("No modifications detected (no update needed): " + dbObj.toString());
    }
    prepareHibernateSearch(obj, OperationType.UPDATE);
    final Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
    session.flush();
    Search.getFullTextSession(session).flushToIndexes();
    afterSaveOrModify(obj);
    if (supportAfterUpdate == true) {
        afterUpdate(obj, dbObjBackup);
    } else {
        afterUpdate(obj, null);
    }
    if (wantsReindexAllDependentObjects == true) {
        reindexDependentObjects(obj);
    }
    return result;
}

From source file:org.projectforge.core.BaseDao.java

License:Open Source License

/**
 * Object will be marked as deleted (boolean flag), therefore undelete is always possible without any loss of data.
 * @param obj/*from   ww  w  .ja v  a 2  s.co m*/
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ)
public void markAsDeleted(final O obj) throws AccessException {
    Validate.notNull(obj);
    if (obj.getId() == null) {
        final String msg = "Could not delete object unless id is not given:" + obj.toString();
        log.error(msg);
        throw new RuntimeException(msg);
    }
    final O dbObj = getHibernateTemplate().load(clazz, obj.getId(), LockMode.PESSIMISTIC_WRITE);
    checkLoggedInUserDeleteAccess(obj, dbObj);
    accessChecker.checkRestrictedOrDemoUser();
    internalMarkAsDeleted(obj);
}

From source file:org.projectforge.core.BaseDao.java

License:Open Source License

@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ)
public void internalMarkAsDeleted(final O obj) {
    if (obj instanceof Historizable == false) {
        log.error(// w w w  .  j  a  va  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 = getHibernateTemplate().load(clazz, obj.getId(), LockMode.PESSIMISTIC_WRITE);
    onSaveOrModify(obj);
    copyValues(obj, dbObj, "deleted"); // If user has made additional changes.
    dbObj.setDeleted(true);
    dbObj.setLastUpdate();
    final Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
    session.flush();
    Search.getFullTextSession(session).flushToIndexes();
    afterSaveOrModify(obj);
    afterDelete(obj);
    getSession().flush();
    log.info("Object marked as deleted: " + dbObj.toString());
}

From source file:org.projectforge.core.BaseDao.java

License:Open Source License

/**
 * Object will be deleted finally out of the data base.
 * @param obj/*from  ww  w  .ja  va 2 s  . co  m*/
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ)
public void delete(final O obj) throws AccessException {
    Validate.notNull(obj);
    if (obj instanceof Historizable) {
        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 = getHibernateTemplate().load(clazz, obj.getId(), LockMode.PESSIMISTIC_WRITE);
    checkLoggedInUserDeleteAccess(obj, dbObj);
    getHibernateTemplate().delete(dbObj);
    log.info("Object deleted: " + obj.toString());
    afterSaveOrModify(obj);
    afterDelete(obj);
}

From source file:org.projectforge.core.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 = getHibernateTemplate().load(clazz, obj.getId(), LockMode.PESSIMISTIC_WRITE);
    onSaveOrModify(obj);//  ww w. j  av a 2  s  . c  om
    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());
    final Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
    session.flush();
    Search.getFullTextSession(session).flushToIndexes();
    afterSaveOrModify(obj);
    afterUndelete(obj);
}

From source file:org.projectforge.framework.persistence.api.BaseDao.java

License:Open Source License

/**
 * This method is for internal use e. g. for updating objects without check access.<br/>
 * Please note: update ignores the field deleted. Use markAsDeleted, delete and undelete methods instead.
 *
 * @param obj/*w w  w . ja v a2s . c  o m*/
 * @param checkAccess If false, any access check will be ignored.
 * @return true, if modifications were done, false if no modification detected.
 */
@Transactional(readOnly = false, propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ)
public ModificationStatus internalUpdate(final O obj, final boolean checkAccess) {
    onSaveOrModify(obj);
    if (checkAccess == true) {
        accessChecker.checkRestrictedOrDemoUser();
    }
    final O dbObj = hibernateTemplate.load(clazz, obj.getId(), LockMode.PESSIMISTIC_WRITE);
    if (checkAccess == true) {
        checkPartOfCurrentTenant(obj, OperationType.UPDATE);
        checkLoggedInUserUpdateAccess(obj, dbObj);
    }
    onChange(obj, dbObj);
    final O dbObjBackup;
    if (supportAfterUpdate == true) {
        dbObjBackup = getBackupObject(dbObj);
    } else {
        dbObjBackup = null;
    }
    final boolean wantsReindexAllDependentObjects = wantsReindexAllDependentObjects(obj, dbObj);
    ModificationStatus result = HistoryBaseDaoAdapter.wrappHistoryUpdate(dbObj, () -> {
        // Copy all values of modified user to database object, ignore field 'deleted'.
        final ModificationStatus tresult = copyValues(obj, dbObj, "deleted");

        if (tresult != ModificationStatus.NONE) {
            BaseDaoJpaAdapter.prepareUpdate(dbObj);
            dbObj.setLastUpdate();
            log.info("Object updated: " + dbObj.toString());
        } else {
            log.info("No modifications detected (no update needed): " + dbObj.toString());
        }
        prepareHibernateSearch(obj, OperationType.UPDATE);
        // TODO HIBERNATE5 Magie nicht notwendig?!?!?!
        if (NO_UPDATE_MAGIC == true) {
            // update doesn't work, because of referenced objects
            hibernateTemplate.merge(dbObj);
        }
        flushSession();
        flushSearchSession();
        return tresult;
    });

    afterSaveOrModify(obj);
    if (supportAfterUpdate == true) {
        afterUpdate(obj, dbObjBackup, result != ModificationStatus.NONE);
        afterUpdate(obj, dbObjBackup);
    } else {
        afterUpdate(obj, null, result != ModificationStatus.NONE);
        afterUpdate(obj, null);
    }
    if (wantsReindexAllDependentObjects == true) {
        reindexDependentObjects(obj);
    }
    return result;
}

From source file:org.projectforge.framework.persistence.api.BaseDao.java

License:Open Source License

/**
 * Object will be marked as deleted (boolean flag), therefore undelete is always possible without any loss of data.
 *
 * @param obj/*from   w ww  .  j  ava 2 s  . co  m*/
 */
@Override
@Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW, isolation = Isolation.REPEATABLE_READ)
public void markAsDeleted(final O obj) throws AccessException {
    Validate.notNull(obj);
    if (obj.getId() == null) {
        final String msg = "Could not delete object unless id is not given:" + obj.toString();
        log.error(msg);
        throw new RuntimeException(msg);
    }
    final O dbObj = hibernateTemplate.load(clazz, obj.getId(), LockMode.PESSIMISTIC_WRITE);
    checkPartOfCurrentTenant(obj, OperationType.DELETE);
    checkLoggedInUserDeleteAccess(obj, dbObj);
    accessChecker.checkRestrictedOrDemoUser();
    internalMarkAsDeleted(obj);
}