Example usage for org.hibernate LockMode NONE

List of usage examples for org.hibernate LockMode NONE

Introduction

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

Prototype

LockMode NONE

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

Click Source Link

Document

No lock required.

Usage

From source file:org.cimmyt.dnast.dao.imp.StInvestigatorHome.java

License:Apache License

public void attachClean(StInvestigator instance) {
    log.debug("attaching clean StInvestigator instance");
    try {/*from w  w w .j  a  v  a  2  s  . c o m*/
        sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
        log.debug("attach successful");
    } catch (RuntimeException re) {
        log.error("attach failed", re);
        throw re;
    }
}

From source file:org.cimmyt.dnast.dao.imp.StSampleidHome.java

License:Apache License

public void attachClean(StSampleid instance) {
    log.debug("attaching clean StSampleid instance");
    try {/*from   ww  w  .j  a  v  a  2  s. c  o m*/
        sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
        log.debug("attach successful");
    } catch (RuntimeException re) {
        log.error("attach failed", re);
        throw re;
    }
}

From source file:org.codehaus.groovy.grails.orm.hibernate.AbstractHibernateSession.java

License:Apache License

public void attach(Object o) {
    hibernateTemplate.lock(o, LockMode.NONE);
}

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();
            }/*w w w  . java 2  s. com*/
            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   www.  j  ava 2  s  . com*/
    }

    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));
    }
}

From source file:org.grails.datastore.gorm.hibernate.HibernateSession.java

License:Apache License

@Override
public void attach(Object o) {
    hibernateTemplate.lock(o, LockMode.NONE);
}

From source file:org.grails.plugins.elasticsearch.index.IndexRequestQueue.java

License:Apache License

/**
 * Execute pending requests and clear both index & delete pending queues.
 *
 * @return Returns an OperationBatch instance which is a listener to the last executed bulk operation. Returns NULL
 *         if there were no operations done on the method call.
 *///from ww w  .jav  a  2  s.co m
public OperationBatch executeRequests() {
    Map<IndexEntityKey, Object> toIndex = new LinkedHashMap<IndexEntityKey, Object>();
    Set<IndexEntityKey> toDelete = new HashSet<IndexEntityKey>();

    cleanOperationBatchList();

    // Copy existing queue to ensure we are interfering with incoming requests.
    synchronized (this) {
        toIndex.putAll(indexRequests);
        toDelete.addAll(deleteRequests);
        indexRequests.clear();
        deleteRequests.clear();
    }

    // If there are domain instances that are both in the index requests & delete requests list,
    // they are directly deleted.
    toIndex.keySet().removeAll(toDelete);

    // If there is nothing in the queues, just stop here
    if (toIndex.isEmpty() && toDelete.isEmpty()) {
        return null;
    }

    BulkRequestBuilder bulkRequestBuilder = elasticSearchClient.prepareBulk();
    //bulkRequestBuilder.setRefresh(true);

    // Execute index requests
    for (Map.Entry<IndexEntityKey, Object> entry : toIndex.entrySet()) {
        SearchableClassMapping scm = elasticSearchContextHolder
                .getMappingContextByType(entry.getKey().getClazz());
        persistenceInterceptor.init();
        try {
            Session session = SessionFactoryUtils.getSession(sessionFactory, true);
            Object entity = entry.getValue();

            // If this not a transient instance, reattach it to the session
            if (session.contains(entity)) {
                session.lock(entity, LockMode.NONE);
                LOG.debug("Reattached entity to session");
            }

            XContentBuilder json = toJSON(entity);

            bulkRequestBuilder.add(elasticSearchClient.prepareIndex().setIndex(scm.getIndexName())
                    .setType(scm.getElasticTypeName()).setId(entry.getKey().getId()) // TODO : Composite key ?
                    .setSource(json));
            if (LOG.isDebugEnabled()) {
                try {
                    LOG.debug("Indexing " + entry.getKey().getClazz() + "(index:" + scm.getIndexName()
                            + ",type:" + scm.getElasticTypeName() + ") of id " + entry.getKey().getId()
                            + " and source " + json.string());
                } catch (IOException e) {
                }
            }
        } finally {
            persistenceInterceptor.destroy();
        }
    }

    // Execute delete requests
    for (IndexEntityKey key : toDelete) {
        SearchableClassMapping scm = elasticSearchContextHolder.getMappingContextByType(key.getClazz());
        if (LOG.isDebugEnabled()) {
            LOG.debug("Deleting object from index " + scm.getIndexName() + " and type "
                    + scm.getElasticTypeName() + " and ID " + key.getId());
        }
        bulkRequestBuilder.add(elasticSearchClient.prepareDelete().setIndex(scm.getIndexName())
                .setType(scm.getElasticTypeName()).setId(key.getId()));
    }

    // Perform bulk request
    OperationBatch completeListener = null;
    if (bulkRequestBuilder.numberOfActions() > 0) {
        completeListener = new OperationBatch(0, toIndex, toDelete);
        operationBatchList.add(completeListener);
        try {
            bulkRequestBuilder.execute().addListener(completeListener);
        } catch (Exception e) {
            throw new IndexException("Failed to index/delete " + bulkRequestBuilder.numberOfActions(), e);
        }
    }

    return completeListener;
}

From source file:org.jasig.portlet.announcements.Exporter.java

License:Apache License

public static void main(String[] args) throws Exception {
    String dir = args[0];/*from w  w  w.ja  v a2 s .c  om*/
    String importExportContext = args[1];
    ApplicationContext context = PortletApplicationContextLocator.getApplicationContext(importExportContext);
    SessionFactory sessionFactory = context.getBean(SESSION_FACTORY_BEAN_NAME, SessionFactory.class);
    IAnnouncementService announcementService = context.getBean(ANNOUNCEMENT_SVC_BEAN_NAME,
            IAnnouncementService.class);

    Session session = sessionFactory.getCurrentSession();
    Transaction transaction = session.beginTransaction();

    JAXBContext jc = JAXBContext.newInstance(Topic.class);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    List<Topic> topics = announcementService.getAllTopics();
    for (Topic topic : topics) {
        if (topic.getSubscriptionMethod() == 4) {
            continue;
        }

        session.lock(topic, LockMode.NONE);
        JAXBElement<Topic> je2 = new JAXBElement<Topic>(new QName("topic"), Topic.class, topic);
        String output = dir + File.separator + UUID.randomUUID().toString() + ".xml";
        System.out.println("Exporting Topic " + topic.getId() + " to file " + output);
        try {
            marshaller.marshal(je2, new FileOutputStream(output));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    transaction.commit();
}

From source file:org.jasig.portlet.data.Exporter.java

License:Apache License

public static void main(String[] args) throws Exception {
    String dir = args[0];/*from w w w . j a v  a2s . c  o  m*/
    String importExportContext = args[1];
    String sessionFactoryBeanName = args[2];
    String modelClassName = args[3];
    String serviceBeanName = args[4];
    String serviceBeanMethodName = args[5];

    ApplicationContext context = PortletApplicationContextLocator.getApplicationContext(importExportContext);
    SessionFactory sessionFactory = context.getBean(sessionFactoryBeanName, SessionFactory.class);
    Class<?> modelClass = Class.forName(modelClassName);

    Object service = context.getBean(serviceBeanName);
    Session session = sessionFactory.getCurrentSession();
    Transaction transaction = session.beginTransaction();

    JAXBContext jc = JAXBContext.newInstance(modelClass);
    Marshaller marshaller = jc.createMarshaller();
    marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

    Method method = service.getClass().getMethod(serviceBeanMethodName);
    List<?> objects = (List<?>) method.invoke(service, null);

    for (Object o : objects) {
        session.lock(o, LockMode.NONE);
        JAXBElement je2 = new JAXBElement(new QName(modelClass.getSimpleName().toLowerCase()), modelClass, o);
        String output = dir + File.separator + UUID.randomUUID().toString() + ".xml";
        try {
            marshaller.marshal(je2, new FileOutputStream(output));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
    transaction.commit();
}

From source file:org.jboss.test.hibernate.timers.TimersFactory.java

License:Open Source License

public void attachClean(Timers instance) {
    log.debug("attaching clean Timers instance");
    try {//from w ww .  j  a v  a 2 s .  c  o m
        sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
        log.debug("attach successful");
    } catch (RuntimeException re) {
        log.error("attach failed", re);
        throw re;
    }
}