Example usage for org.hibernate Query setLong

List of usage examples for org.hibernate Query setLong

Introduction

In this page you can find the example usage for org.hibernate Query setLong.

Prototype

@Deprecated
@SuppressWarnings("unchecked")
default Query<R> setLong(String name, long val) 

Source Link

Document

Bind a named long-valued parameter.

Usage

From source file:com.thoughtworks.go.server.persistence.MaterialRepository.java

License:Apache License

public Modifications getModificationsFor(final MaterialInstance materialInstance, final Pagination pagination) {
    String key = materialModificationsWithPaginationKey(materialInstance);
    String subKey = materialModificationsWithPaginationSubKey(pagination);
    Modifications modifications = (Modifications) goCache.get(key, subKey);
    if (modifications == null) {
        synchronized (key) {
            modifications = (Modifications) goCache.get(key, subKey);
            if (modifications == null) {
                List<Modification> modificationsList = (List<Modification>) getHibernateTemplate()
                        .execute((HibernateCallback) session -> {
                            Query q = session
                                    .createQuery("FROM Modification WHERE materialId = ? ORDER BY id DESC");
                            q.setFirstResult(pagination.getOffset());
                            q.setMaxResults(pagination.getPageSize());
                            q.setLong(0, materialInstance.getId());
                            return q.list();
                        });/*  w  ww . j  ava2 s.  c  o m*/
                if (!modificationsList.isEmpty()) {
                    modifications = new Modifications(modificationsList);
                    goCache.put(key, subKey, modifications);
                }
            }
        }
    }
    return modifications;
}

From source file:com.trailmagic.user.UserLoginModule.java

License:Open Source License

private boolean validate(String username, char[] password) throws Exception {

    boolean valid = false;
    User user;//from   w  ww  .ja  v a  2 s  .c o m
    Session sess = null;

    try {
        sess = m_sessFactory.openSession();

        // validate with the User from hibernate
        Query query = sess.getNamedQuery(USER_BY_SN_QUERY);
        query.setString("screenName", username);

        //            user = (User)query.uniqueResult();
        Object obj = query.uniqueResult();
        //            System.err.println("uniqueResult returned a " + obj.getClass());
        user = (User) obj;
        if (user == null) {
            return false;
        }

        String storedPass = user.getPassword();

        if (storedPass != null && password != null && password.length > 0) {

            String digest = encodePassword(password);
            valid = storedPass.equals(digest);
            //                s_log.debug("digest = " + digest);
        }

        if (valid) {
            m_principals.add(new UserPrincipal(user.getScreenName()));
            query = sess.getNamedQuery(GROUPS_QUERY);
            query.setLong("userId", user.getId());
            Iterator iter = query.iterate();
            Collection<GroupPrincipal> groups = new ArrayList<GroupPrincipal>();
            while (iter.hasNext()) {
                groups.add(new GroupPrincipal(((Group) iter.next()).getName()));
            }
            m_principals.addAll(groups);
        }
    } catch (HibernateException e) {
        s_log.error("Hibernate error validating credentials", e);
    } finally {
        if (sess != null) {
            try {
                sess.close();
            } catch (HibernateException e) {
                s_log.error("Error closing session", e);
            }
        }
    }

    return valid;
}

From source file:com.wx.dao.impl.SignDAOImpl.java

@Override
public Sign findSignById(Long id) {
    String hql = "from Sign as sign where sign.id = :id";
    Query query = session.createQuery(hql);

    query.setLong("id", id);
    List<Sign> list = query.list();

    return list.get(0);
}

From source file:com.wx.dao.impl.SignDAOImpl.java

@Override
public List<Sign> findSignByCustomerId(Long customerId) {
    String hql = "from Sign as sign where sign.customerId = :customerId";
    Query query = session.createQuery(hql);

    query.setLong("customerId", customerId);
    List<Sign> list = query.list();

    return list;/*from www  . j  av  a  2s  .c om*/
}

From source file:com.wx.dao.impl.SignDAOImpl.java

@Override
public List<Sign> findSignByCoacherId(Long coacherId) {
    String hql = "from Sign as sign where sign.coacherId = :coacherId";
    Query query = session.createQuery(hql);

    query.setLong("coacherId", coacherId);
    List<Sign> list = query.list();

    return list;/*from  www  . j  a v  a  2 s  . com*/
}

From source file:com.xpn.xwiki.store.XWikiHibernateStore.java

License:Open Source License

public void saveXWikiDoc(XWikiDocument doc, XWikiContext context, boolean bTransaction) throws XWikiException {
    MonitorPlugin monitor = Util.getMonitorPlugin(context);
    try {//  ww  w  .j  a v a2s.  c  o m
        // Start monitoring timer
        if (monitor != null) {
            monitor.startTimer("hibernate");
        }
        doc.setStore(this);
        // Make sure the database name is stored
        doc.getDocumentReference().setWikiReference(new WikiReference(context.getDatabase()));

        if (bTransaction) {
            checkHibernate(context);
            SessionFactory sfactory = injectCustomMappingsInSessionFactory(doc, context);
            bTransaction = beginTransaction(sfactory, context);
        }
        Session session = getSession(context);
        session.setFlushMode(FlushMode.COMMIT);

        // These informations will allow to not look for attachments and objects on loading
        doc.setElement(XWikiDocument.HAS_ATTACHMENTS, (doc.getAttachmentList().size() != 0));
        doc.setElement(XWikiDocument.HAS_OBJECTS, (doc.getXObjects().size() != 0));

        // Let's update the class XML since this is the new way to store it
        // TODO If all the properties are removed, the old xml stays?
        BaseClass bclass = doc.getXClass();
        if (bclass != null) {
            if (bclass.getFieldList().size() > 0) {
                doc.setXClassXML(bclass.toXMLString());
            } else {
                doc.setXClassXML("");
            }
        }

        if (doc.hasElement(XWikiDocument.HAS_ATTACHMENTS)) {
            saveAttachmentList(doc, context, false);
        }

        // Handle the latest text file
        if (doc.isContentDirty() || doc.isMetaDataDirty()) {
            Date ndate = new Date();
            doc.setDate(ndate);
            if (doc.isContentDirty()) {
                doc.setContentUpdateDate(ndate);
                doc.setContentAuthorReference(doc.getAuthorReference());
            }
            doc.incrementVersion();
            if (context.getWiki().hasVersioning(context)) {
                context.getWiki().getVersioningStore().updateXWikiDocArchive(doc, false, context);
            }

            doc.setContentDirty(false);
            doc.setMetaDataDirty(false);
        } else {
            if (doc.getDocumentArchive() != null) {
                // Let's make sure we save the archive if we have one
                // This is especially needed if we load a document from XML
                if (context.getWiki().hasVersioning(context)) {
                    context.getWiki().getVersioningStore().saveXWikiDocArchive(doc.getDocumentArchive(), false,
                            context);
                }
            } else {
                // Make sure the getArchive call has been made once
                // with a valid context
                try {
                    if (context.getWiki().hasVersioning(context)) {
                        doc.getDocumentArchive(context);
                    }
                } catch (XWikiException e) {
                    // this is a non critical error
                }
            }
        }

        // Verify if the document already exists
        Query query = session
                .createQuery("select xwikidoc.id from XWikiDocument as xwikidoc where xwikidoc.id = :id");
        query.setLong("id", doc.getId());
        if (query.uniqueResult() == null) {
            session.save(doc);
        } else {
            session.update(doc);
            // TODO: this is slower!! How can it be improved?
            // session.saveOrUpdate(doc);
        }

        // Remove objects planned for removal
        if (doc.getXObjectsToRemove().size() > 0) {
            for (BaseObject removedObject : doc.getXObjectsToRemove()) {
                deleteXWikiObject(removedObject, context, false);
            }
            doc.setXObjectsToRemove(new ArrayList<BaseObject>());
        }

        if (bclass != null) {
            bclass.setDocumentReference(doc.getDocumentReference());
            // Store this XWikiClass in the context so that we can use it in case of recursive usage of classes
            context.addBaseClass(bclass);
            // Update instances of the class, in case some properties changed their storage type

            // In case the current document has both a class and instances of that class, we have to take care
            // not to insert duplicate entities in the session
            Map<Integer, BaseObject> localClassObjects = new HashMap<Integer, BaseObject>();
            if (doc.hasElement(XWikiDocument.HAS_OBJECTS)
                    && doc.getXObjects(doc.getDocumentReference()) != null) {
                for (BaseObject obj : doc.getXObjects(doc.getDocumentReference())) {
                    if (obj != null) {
                        localClassObjects.put(obj.getId(), obj);
                    }
                }
            }
            for (PropertyClass prop : (Collection<PropertyClass>) bclass.getFieldList()) {
                // migrate values of list properties
                if (prop instanceof StaticListClass || prop instanceof DBListClass) {
                    ListClass lc = (ListClass) prop;
                    String[] classes = { DBStringListProperty.class.getName(),
                            StringListProperty.class.getName(), StringProperty.class.getName() }; // @see ListClass#newProperty()
                    for (int i = 0; i < classes.length; i++) {
                        String oldclass = classes[i];
                        if (!oldclass.equals(lc.newProperty().getClass().getName())) {
                            Query q = session
                                    .createQuery("select p from " + oldclass + " as p, BaseObject as o"
                                            + " where o.className=? and p.id=o.id and p.name=?")
                                    .setString(0, bclass.getName()).setString(1, lc.getName());
                            for (Iterator it = q.list().iterator(); it.hasNext();) {
                                BaseProperty lp = (BaseProperty) it.next();
                                BaseProperty lp1 = lc.newProperty();
                                lp1.setId(lp.getId());
                                lp1.setName(lp.getName());
                                if (lc.isMultiSelect()) {
                                    List tmp;
                                    if (lp.getValue() instanceof List) {
                                        tmp = (List) lp.getValue();
                                    } else {
                                        tmp = new ArrayList<String>(1);
                                        tmp.add(lp.getValue());
                                    }
                                    lp1.setValue(tmp);
                                } else {
                                    Object tmp = lp.getValue();
                                    if (tmp instanceof List && ((List) tmp).size() > 0) {
                                        tmp = ((List) tmp).get(0);
                                    }
                                    lp1.setValue(tmp);
                                }
                                session.delete(lp);
                                session.save(lp1);
                            }
                        }
                    }
                }
                // migrate values of list properties
                else if (prop instanceof NumberClass) {
                    NumberClass nc = (NumberClass) prop;
                    // @see NumberClass#newProperty()
                    String[] classes = { IntegerProperty.class.getName(), LongProperty.class.getName(),
                            FloatProperty.class.getName(), DoubleProperty.class.getName() };
                    for (int i = 0; i < classes.length; i++) {
                        String oldclass = classes[i];
                        if (!oldclass.equals(nc.newProperty().getClass().getName())) {
                            Query q = session
                                    .createQuery("select p from " + oldclass + " as p, BaseObject as o"
                                            + " where o.className=?" + "  and p.id=o.id and p.name=?")
                                    .setString(0, bclass.getName()).setString(1, nc.getName());
                            for (BaseProperty np : (List<BaseProperty>) q.list()) {
                                BaseProperty np1 = nc.newProperty();
                                np1.setId(np.getId());
                                np1.setName(np.getName());
                                if (nc.getNumberType().equals("integer")) {
                                    np1.setValue(Integer.valueOf(((Number) np.getValue()).intValue()));
                                } else if (nc.getNumberType().equals("float")) {
                                    np1.setValue(Float.valueOf(((Number) np.getValue()).floatValue()));
                                } else if (nc.getNumberType().equals("double")) {
                                    np1.setValue(Double.valueOf(((Number) np.getValue()).doubleValue()));
                                } else if (nc.getNumberType().equals("long")) {
                                    np1.setValue(Long.valueOf(((Number) np.getValue()).longValue()));
                                }
                                session.delete(np);
                                session.save(np1);
                            }
                        }
                    }
                } else {
                    // General migration of properties
                    Query q = session.createQuery("select p from BaseProperty as p, BaseObject as o"
                            + " where o.className=? and p.id=o.id and p.name=? and p.classType <> ?");
                    q.setString(0, bclass.getName());
                    q.setString(1, prop.getName());
                    q.setString(2, prop.newProperty().getClassType());
                    @SuppressWarnings("unchecked")
                    List<BaseProperty> brokenProperties = q.list();
                    for (BaseProperty brokenProperty : brokenProperties) {
                        BaseProperty newProperty = prop.fromString(brokenProperty.toText());
                        BaseObject localObject = localClassObjects.get(brokenProperty.getId());
                        if (localObject != null) {
                            BaseProperty currentProperty = (BaseProperty) localObject.get(prop.getName());
                            if (currentProperty != null) {
                                newProperty = prop.fromString(currentProperty.toText());
                                if (newProperty != null) {
                                    localObject.put(prop.getName(), newProperty);
                                } else {
                                    localObject.put(prop.getName(), brokenProperty);
                                }
                            }
                        }
                        if (newProperty == null) {
                            log.warn("Incompatible data migration when changing field {} of class {}",
                                    prop.getName(), prop.getClassName());
                            continue;
                        }
                        newProperty.setId(brokenProperty.getId());
                        session.delete(brokenProperty);
                        session.save(newProperty);
                    }
                }
            }
        }

        if (doc.hasElement(XWikiDocument.HAS_OBJECTS)) {
            // TODO: Delete all objects for which we don't have a name in the Map
            for (List<BaseObject> objects : doc.getXObjects().values()) {
                for (BaseObject obj : objects) {
                    if (obj != null) {
                        obj.setDocumentReference(doc.getDocumentReference());
                        /* If the object doesn't have a GUID, create it before saving */
                        if (StringUtils.isEmpty(obj.getGuid())) {
                            obj.setGuid(UUID.randomUUID().toString());
                        }
                        saveXWikiCollection(obj, context, false);
                    }
                }
            }
        }

        if (context.getWiki().hasBacklinks(context)) {
            saveLinks(doc, context, true);
        }

        if (bTransaction) {
            endTransaction(context, true);
        }

        doc.setNew(false);

        // We need to ensure that the saved document becomes the original document
        doc.setOriginalDocument(doc.clone());

    } catch (Exception e) {
        Object[] args = { this.defaultEntityReferenceSerializer.serialize(doc.getDocumentReference()) };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_DOC, "Exception while saving document {0}", e,
                args);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false);
            }
        } catch (Exception e) {
        }

        // End monitoring timer
        if (monitor != null) {
            monitor.endTimer("hibernate");
        }
    }
}

From source file:com.xpn.xwiki.store.XWikiHibernateStore.java

License:Open Source License

private void loadAttachmentList(XWikiDocument doc, XWikiContext context, boolean bTransaction)
        throws XWikiException {
    try {/*from   w w w. j  a  va2s  .  c  om*/
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(false, context);
        }
        Session session = getSession(context);

        Query query = session.createQuery("from XWikiAttachment as attach where attach.docId=:docid");
        query.setLong("docid", doc.getId());
        @SuppressWarnings("unchecked")
        List<XWikiAttachment> list = query.list();
        for (XWikiAttachment attachment : list) {
            attachment.setDoc(doc);
        }
        doc.setAttachmentList(list);
        if (bTransaction) {
            endTransaction(context, false, false);
            bTransaction = false;
        }
    } catch (Exception e) {
        e.printStackTrace();
        Object[] args = { doc.getDocumentReference() };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SEARCHING_ATTACHMENT,
                "Exception while searching attachments for documents {0}", e, args);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false, false);
            }
        } catch (Exception e) {
        }
    }
}

From source file:com.xpn.xwiki.store.XWikiHibernateStore.java

License:Open Source License

private void saveAttachment(XWikiAttachment attachment, boolean parentUpdate, XWikiContext context,
        boolean bTransaction) throws XWikiException {
    try {// w w  w. j  av a 2s . c om
        // The version number must be bumped and the date must be set before the attachment
        // metadata is saved. Changing the version and date after calling
        // session.save()/session.update() "worked" (the altered version was what Hibernate saved)
        // but only if everything is done in the same transaction and as far as I know it
        // depended on undefined behavior.
        if (attachment.isContentDirty()) {
            attachment.updateContentArchive(context);
        }

        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(context);
        }
        Session session = getSession(context);

        Query query = session
                .createQuery("select attach.id from XWikiAttachment as attach where attach.id = :id");
        query.setLong("id", attachment.getId());
        if (query.uniqueResult() == null) {
            session.save(attachment);
        } else {
            session.update(attachment);
        }

        // If the attachment content is "dirty" (out of sync with the database)
        if (attachment.isContentDirty()) {
            // We must save the content of the attachment.
            // updateParent and bTransaction must be false because the content should be saved in the same
            // transation as the attachment and if the parent doc needs to be updated, this function will do it.
            context.getWiki().getAttachmentStore().saveAttachmentContent(attachment, false, context, false);
        }

        if (parentUpdate) {
            context.getWiki().getStore().saveXWikiDoc(attachment.getDoc(), context, false);
        }

        if (bTransaction) {
            endTransaction(context, true);
        }

        // Mark the attachment content and metadata as not dirty.
        // Ideally this would only happen if the transaction is committed successfully but since an unsuccessful
        // transaction will most likely be accompanied by an exception, the cache will not have a chance to save
        // the copy of the document with erronious information. If this is not set here, the cache will return
        // a copy of the attachment which claims to be dirty although it isn't.
        attachment.setMetaDataDirty(false);
        if (attachment.isContentDirty()) {
            attachment.getAttachment_content().setContentDirty(false);
        }

    } catch (Exception e) {
        Object[] args = { attachment.getFilename(), attachment.getDoc().getDocumentReference() };
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_ATTACHMENT,
                "Exception while saving attachments for attachment {0} of document {1}", e, args);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false);
            }
        } catch (Exception e) {
        }
    }
}

From source file:com.xpn.xwiki.store.XWikiHibernateStore.java

License:Open Source License

public XWikiLock loadLock(long docId, XWikiContext context, boolean bTransaction) throws XWikiException {
    XWikiLock lock = null;/*from ww  w .j  ava 2 s  . c  o m*/
    try {
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(false, context);
        }
        Session session = getSession(context);

        Query query = session.createQuery("select lock.docId from XWikiLock as lock where lock.docId = :docId");
        query.setLong("docId", docId);
        if (query.uniqueResult() != null) {
            lock = new XWikiLock();
            session.load(lock, new Long(docId));
        }

        if (bTransaction) {
            endTransaction(context, false, false);
        }
    } catch (Exception e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_LOADING_LOCK, "Exception while loading lock", e);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false, false);
            }
        } catch (Exception e) {
        }
    }
    return lock;
}

From source file:com.xpn.xwiki.store.XWikiHibernateStore.java

License:Open Source License

public void saveLock(XWikiLock lock, XWikiContext context, boolean bTransaction) throws XWikiException {
    try {// ww  w . j  ava 2 s. c om
        if (bTransaction) {
            checkHibernate(context);
            bTransaction = beginTransaction(context);
        }
        Session session = getSession(context);

        Query query = session.createQuery("select lock.docId from XWikiLock as lock where lock.docId = :docId");
        query.setLong("docId", lock.getDocId());
        if (query.uniqueResult() == null) {
            session.save(lock);
        } else {
            session.update(lock);
        }

        if (bTransaction) {
            endTransaction(context, true);
        }
    } catch (Exception e) {
        throw new XWikiException(XWikiException.MODULE_XWIKI_STORE,
                XWikiException.ERROR_XWIKI_STORE_HIBERNATE_SAVING_LOCK, "Exception while locking document", e);
    } finally {
        try {
            if (bTransaction) {
                endTransaction(context, false);
            }
        } catch (Exception e) {
        }
    }
}