Example usage for org.hibernate Query setEntity

List of usage examples for org.hibernate Query setEntity

Introduction

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

Prototype

@Deprecated
@SuppressWarnings("unchecked")
Query<R> setEntity(String name, Object val);

Source Link

Document

Bind an instance of a mapped persistent class to a named query parameter.

Usage

From source file:com.eurodyn.uns.dao.hibernate.HibernateChannelDao.java

License:Mozilla Public License

@Override
public List findAllChannelsByModeAndCreator(String mode, User creator, String orderProperty, String order)
        throws DAOException {
    Session session = null;// w w  w.  j  a  v  a 2s  . c  o  m
    try {
        session = getSession();
        Query query = session
                .createQuery("select c from Channel as c where c.mode=:mode and c.creator=:creator order by c."
                        + orderProperty + " " + order);
        query.setString("mode", mode);
        query.setEntity("creator", creator);
        return query.list();
    } catch (HibernateException e) {
        throw new DAOException(e);
    } finally {
        closeSession(session);
    }
}

From source file:com.eurodyn.uns.dao.hibernate.HibernateChannelDao.java

License:Mozilla Public License

@Override
public List findRpcUserChannels(User user, String orderProperty, String order) throws DAOException {
    Session session = null;/*from w  ww.  ja  va 2s  .  co  m*/
    try {
        session = getSession();
        Query query = session
                .createQuery("select c from Channel as c where c.creator=:user and c.mode='PUSH' order by c."
                        + orderProperty + " " + order);
        query.setEntity("user", user);
        return query.list();
    } catch (HibernateException e) {
        throw new DAOException(e);
    } finally {
        closeSession(session);
    }
}

From source file:com.eurodyn.uns.dao.hibernate.HibernateChannelDao.java

License:Mozilla Public License

@Override
public Map findTestEventsForChannel(Channel channel) throws DAOException {
    Session session = null;/*from   w w w.jav  a2  s. c  om*/
    try {
        session = getSession();
        Query query = session
                .createQuery("select e  from Event as e where e.channel=:channel order by e.id desc) ");
        query.setEntity("channel", channel);
        query.setMaxResults(10);
        Map things = new HashMap();
        List eventList = query.list();
        for (Iterator iter = eventList.iterator(); iter.hasNext();) {
            Event event = (Event) iter.next();
            boolean hasTitle = false;
            String ext_id = event.getExtId();
            RDFThing thing = (RDFThing) things.get(ext_id);
            if (thing == null) {
                hasTitle = false;
                thing = new RDFThing(ext_id, event.getRtype());
                thing.setEventId(new Integer(event.getId()));
                thing.setReceivedDate(event.getCreationDate());
                things.put(ext_id, thing);
            }
            Collection event_metadata = event.getEventMetadataSet();
            for (Iterator iterator = event_metadata.iterator(); iterator.hasNext();) {
                EventMetadata em = (EventMetadata) iterator.next();
                String property = em.getProperty();
                String value = em.getValue();

                ArrayList vals = (ArrayList) thing.getMetadata().get(property);
                if (vals != null) {
                    vals.add(value);
                } else {
                    ArrayList nar = new ArrayList();
                    nar.add(value);
                    thing.getMetadata().put(property, nar);
                }

                //thing.getMetadata().put(property, value);
                if (!hasTitle && property.endsWith("/title")) {
                    if (value != null) {
                        thing.setTitle(value);
                    }
                }

            }

        }

        return things;
    } catch (HibernateException e) {
        throw new DAOException(e);
    } finally {
        closeSession(session);
    }
}

From source file:com.floreantpos.model.dao.TerminalDAO.java

License:Open Source License

public void resetCashDrawer(DrawerPullReport report, Terminal terminal, User user, double balance)
        throws Exception {
    Session session = null;//from   www  .jav a2 s. co  m
    Transaction tx = null;

    CashDrawerResetHistory history = new CashDrawerResetHistory();
    history.setDrawerPullReport(report);
    history.setResetedBy(user);
    history.setResetTime(new Date());

    try {
        session = createNewSession();
        tx = session.beginTransaction();

        String hql = "update Ticket t set t.drawerResetted=true where t." + Ticket.PROP_CLOSED //$NON-NLS-1$
                + "=true and t.drawerResetted=false and t.terminal=:terminal"; //$NON-NLS-1$
        Query query = session.createQuery(hql);
        query.setEntity("terminal", terminal); //$NON-NLS-1$
        query.executeUpdate();

        hql = "update PosTransaction t set t.drawerResetted=true where t.drawerResetted=false and t.terminal=:terminal"; //$NON-NLS-1$
        query = session.createQuery(hql);
        query.setEntity("terminal", terminal); //$NON-NLS-1$
        query.executeUpdate();

        terminal.setAssignedUser(null);
        terminal.setOpeningBalance(balance);
        terminal.setCurrentBalance(balance);
        update(terminal, session);
        save(report, session);
        save(history, session);

        DrawerAssignedHistory history2 = new DrawerAssignedHistory();
        history2.setTime(new Date());
        history2.setOperation(DrawerAssignedHistory.CLOSE_OPERATION);
        history2.setUser(user);
        save(history2, session);

        tx.commit();
    } catch (Exception e) {
        try {
            tx.rollback();
        } catch (Exception x) {
        }
        throw e;
    } finally {
        closeSession(session);
    }
}

From source file:com.floreantpos.model.dao.UserDAO.java

License:Open Source License

public int findNumberOfOpenTickets(User user) throws PosException {
    Session session = null;/*w w w .  j  a  v a 2s.c  o  m*/
    Transaction tx = null;

    String hql = "select count(*) from Ticket ticket where ticket.owner=:owner and ticket." //$NON-NLS-1$
            + Ticket.PROP_CLOSED + "settled=false"; //$NON-NLS-1$
    int count = 0;
    try {
        session = getSession();
        tx = session.beginTransaction();
        Query query = session.createQuery(hql);
        query = query.setEntity("owner", user); //$NON-NLS-1$
        Iterator iterator = query.iterate();
        if (iterator.hasNext()) {
            count = ((Integer) iterator.next()).intValue();
        }
        tx.commit();
        return count;
    } catch (Exception e) {
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception e2) {
        }
        throw new PosException(Messages.getString("UserDAO.12"), e); //$NON-NLS-1$
    } finally {
        if (session != null) {
            session.close();
        }
    }
}

From source file:com.googlecode.sarasvati.hib.HibGraphProcess.java

License:Open Source License

@SuppressWarnings("unchecked")
@Override/*from w  w  w  . j a  v a  2s.  com*/
public List<NodeToken> getTokensOnNode(final Node node, final Engine engine) {
    HibEngine hibEngine = (HibEngine) engine;
    String hql = "from HibNodeToken where nodeRef = :nodeRef and process=:process";
    Query query = hibEngine.getSession().createQuery(hql);
    query.setEntity("nodeRef", node);
    query.setEntity("process", this);
    return query.list();
}

From source file:com.ikon.dao.UserConfigDAO.java

License:Open Source License

/**
 * Update user config profile/*from  ww  w.ja  va2s .  c om*/
 */
public static void updateProfile(String ucUser, int upId) throws DatabaseException {
    log.debug("updateProfile({}, {})", ucUser, upId);
    String qs = "update UserConfig uc set uc.profile=:profile where uc.user=:user";
    Session session = null;
    Transaction tx = null;

    try {
        session = HibernateUtil.getSessionFactory().openSession();
        tx = session.beginTransaction();
        Query q = session.createQuery(qs);
        q.setEntity("profile", ProfileDAO.findByPk(upId));
        q.setString("user", ucUser);
        q.executeUpdate();
        HibernateUtil.commit(tx);
    } catch (HibernateException e) {
        HibernateUtil.rollback(tx);
        throw new DatabaseException(e.getMessage(), e);
    } finally {
        HibernateUtil.close(session);
    }

    log.debug("updateProfile: void");
}

From source file:com.iti.evalue.daos.UsersTaskDao.java

public UsersTask selectAssignment(Users user, Task task) {
    session = sessionFactory.getCurrentSession();
    session.beginTransaction();//from w w  w .  j  a  v a  2  s. c  o  m
    Query query = session.createQuery("SELECT u FROM UsersTask u WHERE u.taskId = :t_id AND u.userId = :u_id");
    query.setEntity("t_id", task);
    query.setEntity("u_id", user);
    UsersTask ut = (UsersTask) query.uniqueResult();
    session.getTransaction().commit();
    return ut;
}

From source file:com.jaspersoft.ireport.designer.data.fieldsproviders.hibernate.HQLFieldsReader.java

License:Open Source License

/**
 * Binds a paramter value to a query paramter.
 * //  w ww  .  j  av a 2  s  . c om
 * @param parameter the report parameter
 */
protected void setParameter(Session session, Query query, String hqlParamName, Object parameterValue)
        throws Exception {
    //ClassLoader cl = MainFrame.getMainInstance().getReportClassLoader();

    if (parameterValue == null) {
        query.setParameter(hqlParamName, parameterValue);
        return;
    }

    Class clazz = parameterValue.getClass();
    Type type = (Type) hibernateTypeMap.get(clazz);

    if (type != null) {
        query.setParameter(hqlParamName, parameterValue, type);
    } else if (Collection.class.isAssignableFrom(clazz)) {
        query.setParameterList(hqlParamName, (Collection) parameterValue);
    } else {
        if (session.getSessionFactory().getClassMetadata(clazz) != null) //param type is a hibernate mapped entity
        {
            query.setEntity(hqlParamName, parameterValue);
        } else //let hibernate try to guess the type
        {
            query.setParameter(hqlParamName, parameterValue);
        }
    }
}

From source file:com.jaspersoft.jasperserver.api.metadata.common.service.impl.hibernate.HibernateRepositoryServiceImpl.java

License:Open Source License

@Transactional(propagation = Propagation.REQUIRED)
public List<ResourceLookup> getDependentResources(ExecutionContext context, String uri,
        SearchCriteriaFactory searchCriteriaFactory, int current, int max) {

    final Resource resource = getResource(context, uri);

    if (resource == null) {
        throw new JSException("jsexception.resource.does.not.exist");
    }/*www. j  a v  a 2s . c  om*/

    if (resource instanceof ReportDataSource) {
        //ReportDataSource can have dependent ReportUnit items
        final ReportDataSource dataSource = (ReportDataSource) resource;
        RepoResource repoDS = findByURI(RepoResource.class, uri, true);
        Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
        //TODO GetDependentResourcesIds query can be updated to handle ReportUnit objects too
        org.hibernate.Query query = session.getNamedQuery("GetDependentResourcesIds");
        query.setEntity("dependency", repoDS).setFirstResult(current);
        if (max > 0) {
            query.setMaxResults(max);
        }
        List<Long> depRes = query.list();
        List<ResourceLookup> depResLookup = getResourcesByIdList(depRes);
        return depResLookup;
        //TODO delete if code above proves to work fine
        //            SearchFilter filter = new SearchFilter() {
        //                public void applyRestrictions(String type, ExecutionContext context, SearchCriteria criteria) {
        //                    DetachedCriteria dsCriteria = criteria.createCriteria("dataSource", "ds");
        //                    dsCriteria.add(Restrictions.eq("ds.name", dataSource.getName()));
        //
        //                    DetachedCriteria dsParent = dsCriteria.createCriteria("parent", "dsParent");
        //                    dsParent.add(Restrictions.eq("dsParent.URI", dataSource.getParentFolder()));
        //
        //                    // will use it later on for sorting
        //                    DetachedCriteria folderCriteria = criteria.createCriteria("parent", "f");
        //                }
        //            };
        //
        //            SearchSorter sorter = new SearchSorter() {
        //                public void applyOrder(String type, ExecutionContext context, SearchCriteria criteria) {
        //                    criteria.addOrder(Order.asc("f.URI"));
        //                    criteria.addOrder(Order.asc("name"));
        //                    // by default we retrieving only id's and to be able sort  we had to add property to select clause
        //                    criteria.addProjection(Projections.property("f.URI"));
        //                    criteria.addProjection(Projections.property("name"));
        //                }
        //            };
        //            SearchCriteriaFactory criteriaFactory = searchCriteriaFactory.newFactory(ReportUnit.class.getName());
        //            List<ResourceLookup> resources = getResources(
        //                    context,
        //                    criteriaFactory,
        //                    Arrays.asList(filter),
        //                    sorter,
        //                    new BasicTransformerFactory(),
        //                    current, max);
        //
        //            return resources;

        //TODO: replace 'exist' with right solution, it's hardcoded fix for CE version
    } else if (resource instanceof ReportUnit && exist("com.jaspersoft.ji.adhoc.DashboardResource")) {
        //ReportUnit can have dependent DashboardResource items
        final RepoResource repoResource = getRepoResource(resource);
        SearchFilter filter = new SearchFilter() {
            public void applyRestrictions(String type, ExecutionContext context, SearchCriteria criteria) {
                DetachedCriteria resourcesCriteria = criteria.createCriteria("resources", "res");
                resourcesCriteria.add(Restrictions.eq("res.id", repoResource.getId()));
            }
        };

        SearchSorter sorter = new SearchSorter() {
            @Override
            protected void addOrder(String type, ExecutionContext context, SearchCriteria criteria) {
                criteria.addOrder(Order.asc("name")).addOrder(Order.asc("id"));
            }

            @Override
            protected void addProjection(String type, ExecutionContext context, SearchCriteria criteria) {
            }
        };

        SearchCriteriaFactory criteriaFactory = searchCriteriaFactory
                .newFactory("com.jaspersoft.ji.adhoc.DashboardResource");
        List<ResourceLookup> resources = getResources(context, criteriaFactory, Arrays.asList(filter), sorter,
                new BasicTransformerFactory(), current, max);

        return resources;
    } else {
        return null; //unsupported resource
    }

}