List of usage examples for org.hibernate Session lock
void lock(Object object, LockMode lockMode);
From source file:edu.ku.brc.specify.treeutils.HibernateTreeDataServiceImpl.java
License:Open Source License
/** * Creates a new Hibernate session and associates the given objects with it. * //from ww w . j av a 2s .c om * @param objects the objects to associate with the new session * @return the newly created session */ private Session getNewSession(final Object... objects) { Session session = HibernateUtil.getSessionFactory().openSession(); for (Object o : objects) { if (o != null) { // make sure not to attempt locking an unsaved object DataModelObjBase dmob = (DataModelObjBase) o; if (dmob.getId() != null) { session.lock(o, LockMode.NONE); } } } return session; }
From source file:itensil.repository.hibernate.RepositoryEntity.java
License:Open Source License
/** * //ww w . j a v a 2 s. c o m * @param node * @throws AccessDeniedException * @throws NotFoundException * @throws LockException */ public void removeNode(NodeEntity node) throws AccessDeniedException, NotFoundException, LockException { User caller = SecurityAssociation.getUser(); if (!hasPermission(caller, node, DefaultNodePermission.WRITE)) { throw new AccessDeniedException(node.getUri(), "write"); } /* perhaps a lock check here? but this guy has managed to worked without (under light use) for 2 years */ deepRemoveNode(node, node.getNodeId()); Set parKids = node.getParentNode().getChildEntities(); if (Hibernate.isInitialized(parKids)) { parKids.remove(node); } getManager().fireContentChangeEvent(node, null, ContentEvent.Type.REMOVE); Session session = HibernateUtil.getSession(); session.flush(); session.lock(node, LockMode.NONE); session.evict(node); }
From source file:itensil.workflow.activities.state.ActivityStateStore.java
License:Open Source License
public void passivateToken(Activity token) throws StateException { Session sess = getSession(); for (ActivityStepState state : token.getStates().values()) { if (state.getId() == null) { sess.save(state);//w w w. jav a2s .c o m } else if (state.isFlowDirty()) { sess.update(state); } state.setFlowDirty(false); } sess.lock(token, LockMode.NONE); }
From source file:no.abmu.common.persistence.hibernate3.AbstractBaseDaoImpl.java
License:Open Source License
public void reattach(Object obj) { Session session = SessionFactoryUtils.getSession(getSessionFactory(), true); try {/*from w w w .j a va2 s . c o m*/ session.lock(obj, LockMode.NONE); } catch (HibernateException e) { throw new RuntimeException("Problem reattaching object " + obj.toString(), e); } }
From source file:org.apache.camel.component.hibernate.HibernateConsumer.java
License:Apache License
/** * A strategy method to lock an object with an exclusive lock so that it can * be processed/*from ww w .j a va 2 s . co m*/ * * @param entity the entity to be locked * @param session * @return true if the entity was locked */ protected boolean lockEntity(Object entity, Session session) { if (!getEndpoint().isConsumeDelete() || !getEndpoint().isConsumeLockEntity()) { return true; } try { if (LOG.isDebugEnabled()) { LOG.debug("Acquiring exclusive lock on entity: " + entity); } session.lock(entity, LockMode.WRITE); return true; } catch (Exception e) { if (LOG.isDebugEnabled()) { LOG.debug("Failed to achieve lock on entity: " + entity + ". Reason: " + e, e); } return false; } }
From source file:org.archiviststoolkit.mydomain.NamesDAO.java
License:Open Source License
public int merge(Collection<DomainObject> mergeFrom, DomainObject mergeTo, InfiniteProgressPanel progressPanel) throws MergeException { Session session = SessionFactory.getInstance().openSession(); Transaction tx = session.beginTransaction(); Names nameMergeTo = (Names) mergeTo; session.lock(nameMergeTo, LockMode.NONE); Names name;/* www . j av a 2 s . co m*/ String message; int totalCount = 0; int subjectsToMerge = mergeFrom.size() - 1; int subjectsMerged = 1; for (DomainObject domainObject : mergeFrom) { try { name = (Names) domainObject; if (!name.equals(nameMergeTo)) { session.lock(name, LockMode.NONE); progressPanel.setTextLine( "Merging (record " + subjectsMerged++ + " of " + subjectsToMerge + ")...", 1); progressPanel.setTextLine(name + " -> " + nameMergeTo, 1); int count = 1; int numberOfLinks = name.getArchDescriptionNames().size(); for (ArchDescriptionNames nameLink : name.getArchDescriptionNames()) { try { message = "relationship " + count++ + " of " + numberOfLinks; System.out.println(message); progressPanel.setTextLine(message, 3); nameMergeTo.addArchDesctiption(nameLink); totalCount++; } catch (DuplicateLinkException e) { //do nothing } } session.delete(name); } } catch (HibernateException e) { tx.rollback(); session.close(); throw new MergeException("Error merging names", e); } } session.update(nameMergeTo); try { tx.commit(); } catch (HibernateException e) { tx.rollback(); session.close(); throw new MergeException("Error merging names", e); } session.close(); return totalCount; }
From source file:org.archiviststoolkit.mydomain.ResourcesDAO.java
License:Open Source License
public int merge(Collection<DomainObject> mergeFrom, DomainObject mergeTo, InfiniteProgressPanel progressPanel) throws MergeException { Session session = getLongSession(); Transaction tx = session.beginTransaction(); Resources resourceMergeTo = null; try {//from ww w . j a va 2s . c o m resourceMergeTo = (Resources) findByPrimaryKeyLongSession(mergeTo.getIdentifier()); } catch (LookupException e) { rollBackAndThrowMergeException(session, tx, e); } // session.lock(resourceMergeTo, LockMode.NONE); Resources resource; String message; int totalCount = 0; int resourcesToMerge = mergeFrom.size() - 1; int resourcesMerged = 1; ArrayList<ResourcesComponents> componentsToMove = new ArrayList<ResourcesComponents>(); for (DomainObject domainObject : mergeFrom) { try { resource = (Resources) domainObject; if (!resource.equals(resourceMergeTo)) { session.lock(resource, LockMode.NONE); progressPanel.setTextLine( "Merging (record " + resourcesMerged++ + " of " + resourcesToMerge + ")...", 1); progressPanel.setTextLine(resource + " -> " + resourceMergeTo, 2); totalCount += transferTopLevelComponents(progressPanel, session, tx, resourceMergeTo, resource, componentsToMove); deleteLongSession(resource, false); } } catch (HibernateException e) { rollBackAndThrowMergeException(session, tx, e); } catch (DeleteException e) { rollBackAndThrowMergeException(session, tx, e); } } // now add the componets to the mergeTo resource int count = 1; int numberOfLinks = componentsToMove.size(); resourceMergeTo.resequenceSequencedObjects(); int nextSequenceNumber = resourceMergeTo.getNextSequenceNumber(); for (ResourcesComponents component : componentsToMove) { progressPanel.setTextLine("Adding components " + count++ + " of " + numberOfLinks, 2); component.setSequenceNumber(nextSequenceNumber++); resourceMergeTo.addComponent(component); component.setResource(resourceMergeTo); } progressPanel.setTextLine("Saving record", 2); session.update(resourceMergeTo); tx.commit(); session.close(); return totalCount; }
From source file:org.archiviststoolkit.mydomain.SubjectsDAO.java
License:Open Source License
public int merge(Collection<DomainObject> mergeFrom, DomainObject mergeTo, InfiniteProgressPanel progressPanel) throws MergeException { Session session = SessionFactory.getInstance().openSession(); Transaction tx = session.beginTransaction(); Subjects subjectMergeTo = (Subjects) mergeTo; session.lock(subjectMergeTo, LockMode.NONE); Subjects subject;//from ww w . j a va2 s .c o m String message; int totalCount = 0; int subjectsToMerge = mergeFrom.size() - 1; int subjectsMerged = 1; for (DomainObject domainObject : mergeFrom) { try { subject = (Subjects) domainObject; if (!subject.equals(subjectMergeTo)) { session.lock(subject, LockMode.NONE); progressPanel.setTextLine( "Merging (record " + subjectsMerged++ + " of " + subjectsToMerge + ")...", 1); progressPanel.setTextLine(subject + " -> " + subjectMergeTo, 2); int count = 1; int numberOfLinks = subject.getArchDescriptionSubjects().size(); for (ArchDescriptionSubjects subjectLink : subject.getArchDescriptionSubjects()) { try { message = "relationship " + count++ + " of " + numberOfLinks; System.out.println(message); progressPanel.setTextLine(message, 3); subjectMergeTo.addArchDesctiption(subjectLink.getArchDescription()); totalCount++; } catch (DuplicateLinkException e) { //do nothing } } session.delete(subject); } } catch (HibernateException e) { throw new MergeException("Error merging subjects", e); } } session.update(subjectMergeTo); tx.commit(); session.close(); return totalCount; }
From source file:org.codehaus.groovy.grails.orm.hibernate.metaclass.MergePersistentMethod.java
License:Apache License
@Override protected Object performSave(final Object target, final boolean flush) { return getHibernateTemplate().execute(new HibernateCallback<Object>() { public Object doInHibernate(Session session) throws HibernateException, SQLException { Object merged = session.merge(target); session.lock(merged, LockMode.NONE); if (flush) { getHibernateTemplate().flush(); }//from w w w .j ava 2 s. c o m return merged; } }); }
From source file:org.codehaus.groovy.grails.orm.hibernate.validation.UniqueConstraint.java
License:Apache License
@Override protected void processValidate(final Object target, final Object propertyValue, Errors errors) { if (!unique) { return;/*from w ww.j a va 2s .c o m*/ } final Object id; try { id = InvokerHelper.invokeMethod(target, "ident", null); } catch (Exception e) { throw new GrailsRuntimeException("Target of [unique] constraints [" + target + "] is not a domain instance. Unique constraint can only be applied to to domain classes and not custom user types or embedded instances"); } HibernateTemplate hibernateTemplate = getHibernateTemplate(); if (hibernateTemplate == null) throw new IllegalStateException("Unable use [unique] constraint, no Hibernate SessionFactory found!"); List<?> results = hibernateTemplate.executeFind(new HibernateCallback<List<?>>() { public List<?> doInHibernate(Session session) throws HibernateException { session.setFlushMode(FlushMode.MANUAL); try { boolean shouldValidate = true; Class<?> constraintClass = constraintOwningClass; if (propertyValue != null && DomainClassArtefactHandler.isDomainClass(propertyValue.getClass())) { shouldValidate = session.contains(propertyValue); } if (shouldValidate) { GrailsApplication application = (GrailsApplication) applicationContext .getBean(GrailsApplication.APPLICATION_ID); GrailsDomainClass domainClass = (GrailsDomainClass) application .getArtefact(DomainClassArtefactHandler.TYPE, constraintClass.getName()); if (domainClass != null && !domainClass.isRoot()) { GrailsDomainClassProperty property = domainClass .getPropertyByName(constraintPropertyName); while (property.isInherited() && domainClass != null) { domainClass = (GrailsDomainClass) application.getArtefact( DomainClassArtefactHandler.TYPE, domainClass.getClazz().getSuperclass().getName()); if (domainClass != null) { property = domainClass.getPropertyByName(constraintPropertyName); } } constraintClass = domainClass != null ? domainClass.getClazz() : constraintClass; } Criteria criteria = session.createCriteria(constraintClass) .add(Restrictions.eq(constraintPropertyName, propertyValue)); if (uniquenessGroup != null) { for (Object anUniquenessGroup : uniquenessGroup) { String uniquenessGroupPropertyName = (String) anUniquenessGroup; Object uniquenessGroupPropertyValue = GrailsClassUtils .getPropertyOrStaticPropertyOrFieldValue(target, uniquenessGroupPropertyName); if (uniquenessGroupPropertyValue != null && DomainClassArtefactHandler .isDomainClass(uniquenessGroupPropertyValue.getClass())) { try { // We are merely verifying that the object is not transient here session.lock(uniquenessGroupPropertyValue, LockMode.NONE); } catch (TransientObjectException e) { shouldValidate = false; } } if (shouldValidate) { criteria.add(Restrictions.eq(uniquenessGroupPropertyName, uniquenessGroupPropertyValue)); } else { break; // we aren't validating, so no point continuing } } } if (shouldValidate) { return criteria.list(); } return Collections.EMPTY_LIST; } return Collections.EMPTY_LIST; } finally { session.setFlushMode(FlushMode.AUTO); } } }); if (results.isEmpty()) { return; } boolean reject = false; if (id != null) { Object existing = results.get(0); Object existingId = null; try { existingId = InvokerHelper.invokeMethod(existing, "ident", null); } catch (Exception e) { // result is not a domain class } if (!id.equals(existingId)) { reject = true; } } else { reject = true; } if (reject) { Object[] args = new Object[] { constraintPropertyName, constraintOwningClass, propertyValue }; rejectValue(target, errors, UNIQUE_CONSTRAINT, args, getDefaultMessage(DEFAULT_NOT_UNIQUE_MESSAGE_CODE)); } }