Example usage for org.hibernate SQLQuery list

List of usage examples for org.hibernate SQLQuery list

Introduction

In this page you can find the example usage for org.hibernate SQLQuery list.

Prototype

List<R> list();

Source Link

Document

Return the query results as a List.

Usage

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

License:Apache License

public boolean hasPipelineEverRunWith(final String pipelineName, final MaterialRevisions revisions) {
    return (Boolean) getHibernateTemplate().execute((HibernateCallback) session -> {
        int numberOfMaterials = revisions.getRevisions().size();
        int match = 0;
        for (MaterialRevision revision : revisions) {
            long materialId = findOrCreateFrom(revision.getMaterial()).getId();
            long modificationId = revision.getLatestModification().getId();
            String key = cacheKeyForHasPipelineEverRunWithModification(pipelineName, materialId,
                    modificationId);// w w  w  .  j  a  v  a 2s  .co  m
            if (goCache.get(key) != null) {
                match++;
                continue;
            }
            String sql = "SELECT materials.id" + " FROM pipelineMaterialRevisions"
                    + " INNER JOIN pipelines ON pipelineMaterialRevisions.pipelineId = pipelines.id"
                    + " INNER JOIN modifications on modifications.id  = pipelineMaterialRevisions.torevisionId"
                    + " INNER JOIN materials on modifications.materialId = materials.id"
                    + " WHERE materials.id = ? AND pipelineMaterialRevisions.toRevisionId >= ? AND pipelineMaterialRevisions.fromRevisionId <= ? AND pipelines.name = ?"
                    + " GROUP BY materials.id;";
            SQLQuery query = session.createSQLQuery(sql);
            query.setLong(0, materialId);
            query.setLong(1, modificationId);
            query.setLong(2, modificationId);
            query.setString(3, pipelineName);
            if (!query.list().isEmpty()) {
                match++;
                goCache.put(key, Boolean.TRUE);
            }
        }
        return match == numberOfMaterials;
    });
}

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

License:Apache License

@SuppressWarnings("unchecked")
public List<MatchedRevision> findRevisionsMatching(final MaterialConfig materialConfig,
        final String searchString) {
    return (List<MatchedRevision>) getHibernateTemplate().execute((HibernateCallback) session -> {
        String sql = "SELECT m.*" + " FROM modifications AS m"
                + " INNER JOIN materials mat ON mat.id = m.materialId"
                + " WHERE mat.fingerprint = :finger_print"
                + " AND (m.revision || ' ' || COALESCE(m.username, '') || ' ' || COALESCE(m.comment, '') LIKE :search_string OR m.pipelineLabel LIKE :search_string)"
                + " ORDER BY m.id DESC" + " LIMIT 5";
        SQLQuery query = session.createSQLQuery(sql);
        query.addEntity("m", Modification.class);
        Material material = materialConfigConverter.toMaterial(materialConfig);
        query.setString("finger_print", material.getFingerprint());
        query.setString("search_string", "%" + searchString + "%");
        final List<MatchedRevision> list = new ArrayList<>();
        for (Modification mod : (List<Modification>) query.list()) {
            list.add(material.createMatchedRevision(mod, searchString));
        }/*from   w w  w .  ja v a2 s  .  co m*/
        return list;
    });
}

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

License:Apache License

@SuppressWarnings({ "unchecked" })
public void updatePipelineTimeline(final PipelineTimeline pipelineTimeline,
        final List<PipelineTimelineEntry> tempEntriesForRollback) {
    getHibernateTemplate().execute(new HibernateCallback() {
        private static final int PIPELINE_NAME = 0;
        private static final int ID = 1;
        private static final int COUNTER = 2;
        private static final int MODIFIED_TIME = 3;
        private static final int FINGERPRINT = 4;
        private static final int NATURAL_ORDER = 5;
        private static final int REVISION = 6;
        private static final int FOLDER = 7;
        private static final int MOD_ID = 8;
        private static final int PMR_ID = 9;

        public Object doInHibernate(Session session) throws HibernateException {
            LOGGER.info("Start updating pipeline timeline");
            List<Object[]> matches = retrieveTimeline(session, pipelineTimeline);
            List<PipelineTimelineEntry> newPipelines = populateFrom(matches);
            addEntriesToPipelineTimeline(newPipelines, pipelineTimeline, tempEntriesForRollback);

            updateNaturalOrdering(session, newPipelines);
            LOGGER.info("Pipeline timeline updated");
            return null;
        }/*from  www  . j  a  v  a  2 s  .  c  o  m*/

        private void updateNaturalOrdering(Session session, List<PipelineTimelineEntry> pipelines) {
            for (PipelineTimelineEntry pipeline : pipelines) {
                if (pipeline.hasBeenUpdated()) {
                    updateNaturalOrderForPipeline(session, pipeline.getId(), pipeline.naturalOrder());
                }
            }
        }

        private List<Object[]> loadTimeline(SQLQuery query) {
            long startedAt = System.currentTimeMillis();
            List<Object[]> matches = (List<Object[]>) query.list();
            long duration = System.currentTimeMillis() - startedAt;
            if (duration > 1000) {
                LOGGER.warn("updating in memory pipeline-timeline took: {} ms", duration);
            }
            return matches;
        }

        private List<Object[]> retrieveTimeline(Session session, PipelineTimeline pipelineTimeline) {
            SQLQuery query = session.createSQLQuery(queryExtensions.retrievePipelineTimeline());
            query.setLong(0, pipelineTimeline.maximumId());

            List<Object[]> matches = loadTimeline(query);
            sortTimeLineByPidAndPmrId(matches);
            return matches;
        }

        private void sortTimeLineByPidAndPmrId(List<Object[]> matches) {
            matches.sort((m1, m2) -> {
                long id1 = id(m1);
                long id2 = id(m2);
                if (id1 == id2) {
                    return (int) (pmrId(m1) - pmrId(m2));
                }
                return (int) (id1 - id2);
            });
        }

        private List<PipelineTimelineEntry> populateFrom(List<Object[]> matches) {
            ArrayList<PipelineTimelineEntry> newPipelines = new ArrayList<>();
            if (matches.isEmpty()) {
                return newPipelines;
            }

            Map<String, List<PipelineTimelineEntry.Revision>> revisions = new HashMap<>();

            String name = null;
            long curId = -1;
            Integer counter = null;
            double naturalOrder = 0.0;

            PipelineTimelineEntry entry = null;

            for (int i = 0; i < matches.size(); i++) {
                Object[] row = matches.get(i);
                long id = id(row);
                if (curId != id) {
                    name = pipelineName(row);
                    curId = id;
                    counter = counter(row);
                    revisions = new HashMap<>();
                    naturalOrder = naturalOrder(row);
                }

                String fingerprint = fingerprint(row);

                if (!revisions.containsKey(fingerprint)) {
                    revisions.put(fingerprint, new ArrayList<>());
                }
                revisions.get(fingerprint).add(rev(row));

                int nextI = i + 1;
                if (((nextI < matches.size() && id(matches.get(nextI)) != curId) || //new pipeline instance starts in next record, so capture this one
                nextI == matches.size())) {//this is the last record, so capture it
                    entry = new PipelineTimelineEntry(name, curId, counter, revisions, naturalOrder);
                    newPipelines.add(entry);
                }
            }
            return newPipelines;
        }

        private String folder(Object[] row) {
            return (String) row[FOLDER];
        }

        private PipelineTimelineEntry.Revision rev(Object[] row) {
            return new PipelineTimelineEntry.Revision(modifiedTime(row), stringRevision(row), folder(row),
                    modId(row));
        }

        private long pmrId(Object[] row) {
            return ((BigInteger) row[PMR_ID]).longValue();
        }

        private long modId(Object[] row) {
            return ((BigInteger) row[MOD_ID]).longValue();
        }

        private double naturalOrder(Object[] row) {
            return (Double) row[NATURAL_ORDER];
        }

        private Date modifiedTime(Object[] row) {
            return (Date) row[MODIFIED_TIME];
        }

        private String stringRevision(Object[] row) {
            return (String) row[REVISION];
        }

        private String fingerprint(Object[] row) {
            return String.valueOf(row[FINGERPRINT]);
        }

        private String pipelineName(Object[] row) {
            return (String) row[PIPELINE_NAME];
        }

        private int counter(Object[] row) {
            return row[COUNTER] == null ? -1 : ((BigInteger) row[COUNTER]).intValue();
        }

        private long id(Object[] first) {
            return ((BigInteger) first[ID]).longValue();
        }
    });
}

From source file:com.tim10.glavna_knjiga.dbutils.NaloziUtils.java

public boolean provjeriKontoUKontnomPlanu(int idKonta) {

    int idPreduzeca = UserData.getPreduzece().getIdPreduzece();
    SQLQuery query;

    query = session.createSQLQuery("select kpko.KontniOkvir_id from KontniPlan_has_KontniOkvir kpko "
            + "inner join KontniPlan kp on kpko.KontniPlan_IdKontniPlan = kp.idKOntniPlan "
            + "where kpko.KontniOkvir_id = :idKonta and kp.Preduzece_IdPreduzece = :idPreduzeca");
    query.setParameter("idKonta", idKonta);
    query.setParameter("idPreduzeca", idPreduzeca);

    List<KontniOkvir> result = new ArrayList<KontniOkvir>();

    result = query.list();

    if (result.size() > 0)
        return true;
    else//ww w  . ja  va2s.c  om
        return false;
}

From source file:com.tysanclan.site.projectewok.util.forum.AbstractForumViewContext.java

License:Open Source License

@SuppressWarnings("unchecked")
protected final <U> List<U> listOf(SQLQuery query) {
    return (List<U>) query.list();
}

From source file:com.ulcs.dao.CustomerDAO.java

public List<Customer> getMemberInfo() {
    try {/*from w  w  w  . ja va 2  s  .  com*/
        List<Customer> customer = new ArrayList<Customer>();
        //            Connection con=Teledbc.connector();
        String qry = "Select * from customer";
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Customer.class);
        config.configure("hibernate.cfg.xml");
        SessionFactory factory = config.buildSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();

        SQLQuery query = session.createSQLQuery(qry);
        query.addEntity(Customer.class);
        List rs = query.list();
        session.getTransaction().commit();
        return (List<Customer>) rs;
        //            PreparedStatement pst= con.prepareStatement(qry);
        //            ResultSet rs=pst.executeQuery();
        //            
        //            while(rs.next()){
        //                Customer m=new Customer();
        //                m.setCustomerName(rs.getString("customerName"));
        //                m.setCustomerNumber(rs.getString("customerNumber"));
        //                m.setCustomerAddress(rs.getString("customerAddress"));
        //                m.setCustomerID(rs.getInt("CsID"));
        //                customer.add(m);
        //            }
        //            con.close();
        //            return customer;

    }

    catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.ulcs.dao.CustomerDAO.java

public Customer getCustomer(int customerID) {
    try {/*from w ww.java  2 s  .  c  om*/
        //            Connection con=Teledbc.connector();
        String qry = "Select * from customer where customerID=:CsID";
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(Customer.class);
        config.configure("hibernate.cfg.xml");
        SessionFactory factory = config.buildSessionFactory();
        Session session = factory.getCurrentSession();
        session.beginTransaction();
        SQLQuery query = session.createSQLQuery(qry);
        query.addEntity(Customer.class);
        query.setParameter("CsID", customerID);
        List queryList = query.list();
        session.getTransaction().commit();
        if (queryList != null && queryList.isEmpty()) {
            return null;
        } else {
            return (Customer) queryList.get(0);
        }

        //            PreparedStatement pst= con.prepareStatement(qry);
        //            pst.setInt(1, customerID);
        //            ResultSet rs=pst.executeQuery();
        //            
        //            while(rs.next()){
        //                Customer m=new Customer();
        //                m.setCustomerName(rs.getString("customerName"));
        //                m.setCustomerNumber(rs.getString("customerNumber"));
        //                m.setCustomerAddress(rs.getString("customerAddress"));
        //                m.setCustomerID(rs.getInt("CsID"));
        //                return m;
        //            }
        //            con.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.ulcs.dao.UserDAO.java

public User ValidUser(User user) {
    try {/*w  ww  .ja  v  a 2  s  .  co  m*/

        String qry = "Select * from user where userName =:userName and userPassword =:userPassword";
        AnnotationConfiguration config = new AnnotationConfiguration();
        config.addAnnotatedClass(User.class);
        config.configure("hibernate.cfg.xml");
        SessionFactory factory = config.buildSessionFactory();
        Session session = factory.getCurrentSession();

        session.beginTransaction();
        SQLQuery query = session.createSQLQuery(qry);
        query.addEntity(User.class);
        query.setParameter("userName", user.getUserName());
        query.setParameter("userPassword", user.getUserPassword());
        List rs = query.list();
        session.getTransaction().commit();
        if (rs != null) {
            return user;
            //    return (User) rs;

        } else
            return null;

    } catch (Exception e) {
        e.printStackTrace();

    }
    return null;
}

From source file:com.upcera.ddx.dao.user.impl.UserDaoImpl.java

@Override
public List<Map<String, Object>> getSessionUserGroupUnit(Integer mainUserId) throws Exception {
    List<Map<String, Object>> result = new ArrayList<Map<String, Object>>();
    String sql = "select a.email,a.last_name,b.lab_name as name,'lab_login' as logType,a.password from ddx_user a,ddx_lab b where a.lab_id = b.lab_id and a.parent_id =:mainId union all select a.email,a.last_name,b.name,'practice_login' as logType,a.password from ddx_user a,ddx_practice b where a.practice_id = b.practice_id and a.parent_id =:mainId";
    SQLQuery query = getSession().createSQLQuery(sql);
    query.setInteger("mainId", mainUserId);
    List<Object> objList = query.list();
    for (int i = 0; i < objList.size(); i++) {
        Object[] obj = (Object[]) objList.get(i);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("userEmal", obj[0]);
        map.put("userLastName", obj[1]);
        map.put("unitName", obj[2]);
        map.put("logType", obj[3]);
        map.put("password", obj[4]);
        result.add(map);/*w  ww  .  j a v  a2s . c  om*/
    }
    return result;
}

From source file:com.userweave.csv.questionnaire.RrtToCsv.java

License:Open Source License

@SuppressWarnings("unchecked")
private List<Object[]> getRrtResult(RrtConfigurationEntity configuration) {
    QueryObject queryObject = rrtResultDao.createQuery(configuration, null);

    queryObject.setResult("{result.*}, se.id as surveyexec_id");

    SQLQuery q = new QueryTemplate(queryObject).createSqlQuery(getCurrentSession());

    q.addEntity("result", RrtResult.class);
    q.addScalar("surveyexec_id", Hibernate.INTEGER);
    return q.list();
}