Example usage for org.hibernate Query getQueryString

List of usage examples for org.hibernate Query getQueryString

Introduction

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

Prototype

String getQueryString();

Source Link

Document

Get the query string.

Usage

From source file:project.dao.ShareFileDAO.java

public static ShareFile getShareFileByAccountUseAndIdFile(Account accountUses, Document document) {
    ShareFile shareFile = null;/*from   w  w  w.j  av  a2s .  co m*/
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        Query query = session
                .createQuery("FROM ShareFile WHERE id_account_use = :id_account_use AND id_file = :id_file");
        System.out.println("ShareFileDAO: " + query.getQueryString());
        query.setParameter("id_account_use", accountUses.getIdaccount());
        query.setParameter("id_file", document.getIdfile());
        List list = query.list();
        if (list != null && list.size() > 0) {
            shareFile = (ShareFile) list.get(0);
        }
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        e.printStackTrace();
    } finally {
        session.close();
    }
    return shareFile;
}

From source file:project.dao.ShareFileDAO.java

public static ShareFile getShareFileByAccountUseAndIdFile(Account accountUses, int document) {
    ShareFile shareFile = null;/*from   www  . ja va  2 s  . c  om*/
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();
        Query query = session.createQuery(
                "FROM ShareFile WHERE id_account_use = :id_account_use AND id_file = :id_file AND id_account_use <> id_account_share ");
        System.out.println("ShareFileDAO: " + query.getQueryString());
        query.setParameter("id_account_use", accountUses.getIdaccount());
        query.setParameter("id_file", document);
        List list = query.list();
        if (list != null && list.size() > 0) {
            shareFile = (ShareFile) list.get(0);
        }
        tx.commit();
    } catch (HibernateException e) {
        if (tx != null) {
            tx.rollback();
        }
        e.printStackTrace();
    } finally {
        session.close();
    }
    return shareFile;
}

From source file:QueryStore.QueryStoreAPI.java

License:Apache License

/**
 * Calculate the result set hash. This is currently a dummy method. Implement your own hashing scheme here.
 *
 * @param query//from w w w  .  j  av a  2s. co  m
 */
public String calculateResultSetHashFull(Query query) {

    //@Todo Replace this String with a real function
    // Calculates a random string for test purposes.

    ResultSetVerificationAPI resultSetVerification = new ResultSetVerificationAPI();
    String resultSetHash = resultSetVerification.calculateFullHashOfTheQuery(query.getQueryString());

    return resultSetHash;
}

From source file:scotip.app.dao.sounds.SoundDaoImpl.java

License:Open Source License

@Override
public List<SoundLibrary> getSoundsFromList(String[] slugs) {
    Query query = getSession().createQuery("from SoundLibrary WHERE slug IN :slugs");
    query.setParameterList("slugs", slugs);
    System.out.println(query.getQueryString());
    return query.list();
}

From source file:scotip.app.dao.switchboard.CallDaoImpl.java

License:Open Source License

@Override
public List<IncomingCallsLogsWeek> getIncomingCallsByWeek(Company company) {

    Query query = getSession().createQuery(
            "select count(*) as callsNb, day(timestamp) as day, month(timestamp) as month from CallLog cl WHERE cl.switchboard.company = :cmp "
                    + " AND cast(cl.timestamp as date) between :startDate AND :endDate"
                    + " group by day(cl.timestamp), month(cl.timestamp)");

    query.setParameter("cmp", company);

    // months/*ww w  .j ava  2s. c o  m*/
    GregorianCalendar endDate = new GregorianCalendar();
    GregorianCalendar startDate = new GregorianCalendar();
    startDate.add(Calendar.DAY_OF_MONTH, -6);

    query.setParameter("startDate", startDate.getTime());
    query.setParameter("endDate", endDate.getTime());
    List list = query.list();

    List<IncomingCallsLogsWeek> callsLogsWeeks = new ArrayList<>();

    System.out.println(query.getQueryString());
    System.out.println("ResultSQL: " + list.size());

    // associate
    for (Object object : list) {
        Object[] result = (Object[]) object;
        IncomingCallsLogsWeek incoming = new IncomingCallsLogsWeek();
        incoming.setTotal(((Long) result[0]));
        incoming.setDay(((Integer) result[1]));
        incoming.setMonth(((Integer) result[2]));
        callsLogsWeeks.add(incoming);
    }

    return callsLogsWeeks;
}

From source file:Servlets.contServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from   w w  w.  j  a v a 2s .  c om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);
    if (request.getParameter("cont") != null) {
        HybernateUtil hu = new HybernateUtil();
        SessionFactory sessionFactory = hu.getSessionFactory();
        Session session = sessionFactory.getCurrentSession();
        Transaction tx = session.beginTransaction();
        System.out.println("cretaied sessions");

        String queryString = "SELECT * FROM Office";

        Query query = session.createSQLQuery(queryString);
        System.out.println("Query::::" + query.getQueryString().toString());
        ;
        List queryList = query.list();

        statefulBean sfb = new statefulBean();
        sfb.setOfficeList(queryList);
        request.getRequestDispatcher("homecasual.jsp").forward(request, response);
        tx.commit();
        System.out.println(
                "txcommit.............................................................................");
        hu.close();
    }
}

From source file:Servlets.loginServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*  w  w  w.j a v a 2s  .  c o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getParameter("Submit") != null) {
        System.out.println("Submit pressed");
        String user = request.getParameter("username");
        String pass = request.getParameter("password");
        HybernateUtil hu = new HybernateUtil();
        SessionFactory sessionFactory = hu.getSessionFactory();

        //connects to the database
        //and gets the login info for the username that we got from the textboxes
        Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        System.out.println("Session beginTransaction");

        String queryString = "Select * from Login where Login.username= :user";
        Query query = session.createSQLQuery(queryString);
        System.out.println("querylist made");
        query.setParameter("user", user);
        List loginlist = query.list();
        Object[] obj = null;
        for (Object o : loginlist) {
            obj = (Object[]) o;
            System.out.println(obj[0]);
        }
        System.out.println("added query.list to List ");
        session.getTransaction().commit();
        System.out.println("commit");
        int id = Integer.parseInt(obj[0].toString());
        String gotname = obj[1].toString();
        String gotpass = obj[2].toString();
        String gotstatus = obj[3].toString();

        session = sessionFactory.openSession();
        session.beginTransaction();
        User u = new User();
        System.out.println("new user");
        u = (User) session.get(User.class, id);
        session.getTransaction().commit();
        System.out.println("commit");

        //checks to see what kind of member it is and if the username and password matches
        //ex admin or member
        //also some error handling
        for (int i = 0; i < loginlist.size(); i++) {
            System.out.println("in for loop");

            if (gotname.equals(user) && gotpass.equals(pass)) {
                System.out.println("Success");
                statefulBean stb = new statefulBean();
                stb.setName(u.getName());
                stb.setAddres(u.getAdress());
                stb.setMail(u.getEmail());
                stb.setPhone(u.getPhone());
                stb.setLoggedIn(1);
                try {

                    if (gotstatus.equals("member")) {
                        session = sessionFactory.getCurrentSession();
                        session.beginTransaction();
                        queryString = "SELECT * FROM Office";
                        query = session.createSQLQuery(queryString);
                        System.out.println("Query::::" + query.getQueryString().toString());
                        ;
                        request.setAttribute("Loc", query.list());
                        request.setAttribute("Username", gotname);
                        System.out.println("member");
                        request.getRequestDispatcher("homemember.jsp").forward(request, response);
                    } else if (gotstatus.equals("admin")) {
                        request.setAttribute("Username", gotname);
                        System.out.println("admin");
                        request.getRequestDispatcher("homeadmin.jsp").forward(request, response);
                    }

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

            } else {
                String error = "Your Username and/or Password dont exist";
                System.out.println("redirect to login in for");
                request.setAttribute("error", error);
                request.getRequestDispatcher("payment.jsp").forward(request, response);
            }
        }
        if (obj.length == 0) {
            String error = "Your Username and/or Password dont exist";
            System.out.println("redirekt to login utside for");
            request.setAttribute("error", error);
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
        //        hu.close();
    }

    processRequest(request, response);
}

From source file:spms.server.controller.ActiveGame.java

public void joinToGame(String data) {
    try {/* ww  w .j  a  va  2  s. c  om*/
        //this method receive game data that chosen by clients to join it

        JSONParser parser = new JSONParser();
        Object obj = parser.parse(data);

        JSONObject jobj = (JSONObject) obj;
        Integer gameId = Integer.parseInt(jobj.get("gameId").toString());

        Session dbconn = HibernateUtil.getSessionFactory().openSession();
        dbconn.beginTransaction();
        Query q = dbconn.createQuery("Select g from ActiveGames g where g.activeGameId=:id").setParameter("id",
                gameId);
        ActiveGames ags = (ActiveGames) q.uniqueResult();
        dbconn.close();

        dbconn = HibernateUtil.getSessionFactory().openSession();
        dbconn.beginTransaction();
        q = dbconn.createQuery(
                "Select t from ActiveGames g,GameType t where g.activeGameId=:id and t.gameId=g.gameType.gameId")
                .setParameter("id", gameId);
        System.out.println(q.getQueryString());
        GameType gt = (GameType) q.uniqueResult();
        dbconn.close();

        Connections gameCon = new Connections();

        gameCon.setClientIp(session.server.getRemoteSocketAddress().toString());
        gameCon.setActiveGames(ags);
        gameCon.setSessionId(session.conn_index);
        gameCon.setConnectTime(new Date());
        gameCon.setStatus(SysConst.CONNECTION_STATUS_WAITING);

        dbconn = HibernateUtil.getSessionFactory().openSession();
        dbconn.beginTransaction().begin();
        dbconn.save(gameCon);
        dbconn.beginTransaction().commit();
        dbconn.close();

        String dom = new String(Files.readAllBytes((new File(gt.getDomainFile()).toPath())));
        dom = dom.replace("\n", SysConst.ENDL);
        session.send(SysConst.DOMAIN_FILE + dom);

    } catch (ParseException ex) {
        Logger.getLogger(ActiveGame.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(ActiveGame.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:ubic.gemma.persistence.service.association.coexpression.CoexpressionDaoImpl.java

License:Apache License

/**
 * Gene-focused query. Use this if you don't care about which data sets are involved (or if there are many data
 * sets), for a relatively small number of genes. This DOES NOT cache the results, the caller has to do that. It
 * also does not check the cache.//from   w w w  .jav a  2s .c o m
 *
 * @param geneIds   the gene IDs
 * @param className the class name
 * @return results without any limit on the size, each list is already sorted.
 */
private Map<Long, List<CoexpressionValueObject>> getCoexpressionFromDbViaGenes(Collection<Long> geneIds,
        String className) {

    Query q = this.buildQuery(geneIds, className);
    StopWatch timer = new StopWatch();
    timer.start();
    List<Gene2GeneCoexpression> rawResults = q.list();

    if (timer.getTime() > 1000) {
        CoexpressionDaoImpl.log.debug("Initial coexp query for " + geneIds.size() + "genes took "
                + timer.getTime() + "ms: " + rawResults.size() + " results");
        CoexpressionDaoImpl.log.debug("Query was: " + q.getQueryString());
    }

    if (rawResults.isEmpty())
        return new HashMap<>();

    timer.reset();
    timer.start();
    Map<Long, List<CoexpressionValueObject>> results = this.convertToValueObjects(rawResults, geneIds);

    for (Long g : results.keySet()) {
        List<CoexpressionValueObject> gc = results.get(g);
        Collections.sort(gc);
    }

    if (timer.getTime() > 100) {
        CoexpressionDaoImpl.log.debug("Convert to value objects, filter, sort and finish " + rawResults.size()
                + " results: " + timer.getTime() + "ms");
    }

    return results;
}

From source file:uk.ac.kcl.iop.brc.core.pipeline.dncpipeline.data.DNCWorkUnitDao.java

License:Open Source License

private Object getObjectFromCoordinate(DNCWorkCoordinate coordinate) {
    SessionWrapper sessionWrapper = getCurrentSourceSession();
    try {//from   ww  w .j  av  a  2s.c  o m
        Query coordinateQuery = sessionWrapper.getNamedQuery("getObjectFromCoordinate");
        String queryString = coordinateQuery.getQueryString();
        queryString = queryString.replace(":sourceTable", coordinate.getSourceTable())
                .replace(":sourceColumn", coordinate.getSourceColumn())
                .replace(":pkColumnName", coordinate.getPkColumnName())
                .replace(":id", Long.toString(coordinate.getIdInSourceTable()));

        List result = getSQLResultFromSource(queryString);

        if (CollectionUtils.isEmpty(result)) {
            throw new WorkCoordinateNotFound("Coordinate is invalid. No data found at " + coordinate);
        }

        return result.get(0);
    } finally {
        sessionWrapper.closeSession();
    }
}