Example usage for org.hibernate Query setTimestamp

List of usage examples for org.hibernate Query setTimestamp

Introduction

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

Prototype

@Deprecated
@SuppressWarnings("unchecked")
default Query<R> setTimestamp(String name, Date value) 

Source Link

Document

Bind the value and the time of a given Date object to a named query parameter.

Usage

From source file:com.spr.hib.domain.NativeApiIllustrationTest.java

License:Open Source License

public void testBasicUsage() {

    Session session = sessionFactory.openSession();
    session.getTransaction().begin();//from  w  w w .jav a 2  s.  c o  m

    Thing thing = new Thing();
    Person p = new Person();
    p.setName("abwwddw");
    p.setEmail("EALL@em42ail.com");
    thing.setTitle("via person1");
    thing.setStatus(Status.FINISHED);
    thing.setOwner(p);
    Set<Thing> things = new HashSet<Thing>();
    things.add(thing);

    p.setThings(things);
    session.save(p);
    //session.save(thing);

    session.getTransaction().commit();
    session.close();

    session = sessionFactory.openSession();
    session.beginTransaction();
    Query query = session.createQuery("from Thing WHERE startDate <=:now ");
    query.setTimestamp("now", new Date());
    List<Thing> result = query.list();
    for (Thing thing2 : (List<Thing>) result) {
        System.out.println(thing2.getTags().size());
    }
    session.getTransaction().commit();
    session.close();

}

From source file:com.thoughtworks.go.server.dao.AccessTokenSqlMapDao.java

License:Apache License

public void updateLastUsedTime(Map<Long, Timestamp> accessTokenIdToLastUsedTimestamp) {
    transactionTemplate.execute(transactionCallback -> {
        final Session currentSession = sessionFactory.getCurrentSession();

        accessTokenIdToLastUsedTimestamp.keySet().forEach(tokenId -> {
            final Query query = currentSession
                    .createQuery("UPDATE AccessToken SET lastUsed = :lastUsed WHERE id = :id");
            query.setLong("id", tokenId);
            query.setTimestamp("lastUsed", accessTokenIdToLastUsedTimestamp.get(tokenId));
            query.executeUpdate();// ww w.jav a 2  s . c o m
        });

        return Boolean.TRUE;
    });
}

From source file:com.trifork.stamdata.Fetcher.java

License:Mozilla Public License

@SuppressWarnings("unchecked")
@Transactional/*  w w  w. j  a va2 s  . c  o m*/
public <T extends TemporalEntity> T fetch(Instant instant, Class<T> type, Object id) throws SQLException {
    checkNotNull(instant, "instant");
    checkNotNull(type, "type");
    checkNotNull(id, "id");

    // The database uses open/closed validity intervals: [a;b[
    // When a record is 'closed' (no longer valid) its ValidTo
    // is set to the same value as its ValidFrom. Therefore the
    // ValidTo must be checked using the '<' operator.

    String keyColumn = Entities.getIdColumnName(type);
    String entityName = type.getCanonicalName();

    Query query = session.createQuery(format(
            "FROM %s WHERE %s = :id AND ValidFrom <= :instant AND :instant < ValidTo", entityName, keyColumn));

    query.setParameter("id", id);
    query.setTimestamp("instant", instant.toDate());

    // This query should only ever return a single result or the database's
    // structure has been corrupted. So we want an exception to be thrown.

    return (T) query.uniqueResult();
}

From source file:com.trifork.stamdata.Fetcher.java

License:Mozilla Public License

@SuppressWarnings("unchecked")
@Transactional/*from  ww w. j  a  v  a  2 s .  c o  m*/
public <T extends TemporalEntity> List<T> fetch(Instant instant, Class<T> type, String column, Object value,
        Type sqlType) {
    checkNotNull(instant, "instant");
    checkNotNull(type, "type");
    checkNotNull(column, "column");
    checkNotNull(value, "value");

    String entityName = type.getCanonicalName();
    Query query = session.createQuery(format(
            "FROM %s WHERE %s = :value AND ValidFrom <= :instant AND :instant < ValidTo", entityName, column));

    query.setParameter("value", value, sqlType);
    query.setTimestamp("instant", instant.toDate());

    return (List<T>) query.list();
}

From source file:com.trifork.stamdata.Fetcher.java

License:Mozilla Public License

@SuppressWarnings("unchecked")
@Transactional//w  w w  .  ja  v  a2  s .  c o  m
public <T extends TemporalEntity> List<T> fetch(Instant instant, Class<T> type, String column, Object value) {
    checkNotNull(instant, "instant");
    checkNotNull(type, "type");
    checkNotNull(column, "column");
    checkNotNull(value, "value");

    String entityName = type.getCanonicalName();
    Query query = session.createQuery(format(
            "FROM %s WHERE %s = :value AND ValidFrom <= :instant AND :instant < ValidTo", entityName, column));

    query.setParameter("value", value);
    query.setTimestamp("instant", instant.toDate());

    return (List<T>) query.list();
}

From source file:com.trifork.stamdata.Fetcher.java

License:Mozilla Public License

@SuppressWarnings("unchecked")
@Transactional//from  w  ww  . jav  a  2s . co m
public <T extends TemporalEntity> List<T> fetch(Instant instant, Class<T> type,
        Map<String, Object> columnAndValue) {
    checkNotNull(instant, "instant");
    checkNotNull(type, "type");
    checkNotNull(columnAndValue, "columnAndValue");
    Preconditions.checkArgument(!columnAndValue.isEmpty(),
            "You must specify a map containing column name -> value pairs");

    StringBuffer whereClause = new StringBuffer();
    for (String columnName : columnAndValue.keySet()) {
        if (whereClause.length() > 0) {
            whereClause.append(" AND ");
        }
        whereClause.append(columnName + " = :" + columnName);
    }
    whereClause.append(" AND ValidFrom <= :instant AND :instant < ValidTo");

    String entityName = type.getCanonicalName();
    Query query = session.createQuery(format("FROM %s WHERE " + whereClause.toString(), entityName));
    query.setTimestamp("instant", instant.toDate());

    // Set remaining variables on query
    for (String columnName : columnAndValue.keySet()) {
        query.setParameter(columnName, columnAndValue.get(columnName));
    }

    return (List<T>) query.list();
}

From source file:com.zhengxuetao.gupiao.dao.impl.DayDAOImpl.java

@Override
public List<DayData> findDayDataList(Long id, Timestamp startDate, Timestamp endDate) {
    Query query = getSession().createQuery("FROM DayData d WHERE d.financeId=:id AND d.time>=:startDate "
            + "AND d.time <=:endDate ORDER BY d.time ASC");
    query.setLong("id", id);
    query.setTimestamp("startDate", startDate);
    query.setTimestamp("endDate", endDate);
    return query.list();
}

From source file:cz.zcu.kiv.eegdatabase.data.dao.SimpleExperimentDao.java

License:Apache License

public List<Experiment> getExperimentSearchResults(List<SearchRequest> requests, int personId)
        throws NumberFormatException {
    List<Experiment> results;
    boolean ignoreChoice = false;
    int index = 0;
    List<Date> datas = new ArrayList<Date>();
    String hqlQuery = "from Experiment e left join fetch e.hardwares hw where ";
    try {/*from  w  w w. j  av  a 2 s . c  o m*/
        for (SearchRequest request : requests) {
            if (request.getCondition().equals("")) {
                if (request.getChoice().equals("")) {
                    ignoreChoice = true;
                }
                continue;
            }
            if (!ignoreChoice) {
                hqlQuery += request.getChoice();

            }
            if (request.getSource().equals("usedHardware")) {
                hqlQuery += " (lower(hw.title) like lower('%" + request.getCondition()
                        + "%') or lower(hw.type) like lower('%" + request.getCondition() + "%'))";

            } else if (request.getSource().endsWith("Time")) {
                String[] times = request.getCondition().split(" ");
                if (times.length == 1) {
                    datas.add(ControllerUtils.getDateFormat().parse(request.getCondition()));
                }
                if (times.length > 1) {
                    datas.add(ControllerUtils.getDateFormatWithTime().parse(request.getCondition()));
                }
                hqlQuery += "e." + request.getSource() + getCondition(request.getSource()) + " :ts" + index;
                index++;

            } else if (request.getSource().startsWith("age")) {
                hqlQuery += "e.personBySubjectPersonId.dateOfBirth" + getCondition(request.getSource()) + "'"
                        + getPersonYearOfBirth(request.getCondition()) + "'";
            } else if (request.getSource().endsWith("gender")) {
                hqlQuery += "e.personBySubjectPersonId.gender = '"
                        + request.getCondition().toUpperCase().charAt(0) + "'";
            } else {
                hqlQuery += "lower(e." + request.getSource() + ")" + getCondition(request.getSource())
                        + "lower('%" + request.getCondition() + "%')";
            }
            ignoreChoice = false;
        }
        //            hqlQuery += " and e.experimentId IN(SELECT e.experimentId FROM Experiment e LEFT JOIN e.researchGroup.researchGroupMemberships membership WHERE e.privateExperiment = false OR membership.person.id = " + personId + ")";
        hqlQuery += " and e.experimentId IN(SELECT epc.experiment.experimentId from ExperimentPackageConnection epc, ExperimentPackageLicense epl, "
                + " PersonalLicense pl where "
                + "epc.experimentPackage.experimentPackageId = epl.experimentPackage.experimentPackageId and "
                + "epl.license.licenseId = pl.license.licenseId and " + "pl.person.personId = " + personId
                + ")";
        Session ses = getSession();
        Query q = ses.createQuery(hqlQuery);
        int i = 0;
        for (Date date : datas) {
            q.setTimestamp("ts" + i, date);
            i++;
        }

        results = q.list();
    } catch (ParseException e) {
        throw new RuntimeException("Inserted date and time is not in valid format \n"
                + "Valid format is DD/MM/YYYY HH:MM or DD/MM/YYYY.");
    } catch (Exception e) {
        return new ArrayList<Experiment>();
    }

    return results;
}

From source file:de.fhdo.terminologie.helper.HQLParameterHelper.java

License:Apache License

public void applySQLParameter(Query q) {
    Iterator<String> it = parameterMap.keySet().iterator();

    while (it.hasNext()) {
        String key = it.next();//w  ww. ja v a 2  s.  c o m
        HQLObject obj = parameterMap.get(key);

        String s = "";

        if (obj.obj instanceof String) {
            s = "%" + obj.obj.toString() + "%";
            q.setString("s_" + obj.fieldName, s);
        } else if (obj.obj instanceof java.util.Date) {
            //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //s = sdf.format(obj.obj);

            //q.setDate("s_" + obj.fieldName, (java.util.Date)obj.obj);
            q.setTimestamp("s_" + obj.fieldName, (java.util.Date) obj.obj);
            //logger.debug("SDF: " + sdf.format(obj.obj));
        } else if (obj.obj instanceof Boolean) {
            //s = Boolean.parseBoolean(obj.obj.toString()) ? "1" : "0";
            q.setBoolean("s_" + obj.fieldName, (Boolean) obj.obj);
            //logger.debug("Bool: " + s);
        } else if (obj.obj instanceof Integer) {
            //s = ((Integer)obj.obj).toString();
            q.setInteger("s_" + obj.fieldName, (Integer) obj.obj);
        } else if (obj.obj instanceof Long) {
            //s = ((Integer)obj.obj).toString();
            q.setLong("s_" + obj.fieldName, (Long) obj.obj);
        } else {
            s = obj.obj.toString();
            q.setString("s_" + obj.fieldName, s);

            logger.warn("Typ nicht gefunden: " + obj.obj.getClass().getCanonicalName());
        }

    }
}

From source file:de.innovationgate.webgate.api.jdbc.WGDatabaseImpl.java

License:Open Source License

public List<WGUpdateLog> getUpdateLogs(Comparable fromRevision) throws WGAPIException {

    try {/*  w  w  w  .ja va  2  s .  c  om*/
        Iterator logEntries;
        if (_ddlVersion >= WGDatabase.CSVERSION_WGA5) {
            Query logEntriesQ = getSession().createQuery(
                    "from de.innovationgate.webgate.api.jdbc.LogEntry as logentry where id > :start order by id asc");
            logEntriesQ.setLong("start", ((Long) fromRevision).longValue());
            logEntries = logEntriesQ.iterate();

        } else {
            Date cutoff = (Date) fromRevision;
            Query logEntriesQ = getSession().createQuery(
                    "from de.innovationgate.webgate.api.jdbc.LogEntry as logentry where logtime >= :start order by logtime asc");
            logEntriesQ.setTimestamp("start", new java.sql.Timestamp(cutoff.getTime()));
            logEntries = logEntriesQ.iterate();
        }

        List wgLogs = new ArrayList();
        LinkedMap wgLogsByTarget = new LinkedMap();
        Map conflictTargets = new HashMap();

        LogEntry entry;

        // First pass: Create update logs
        while (logEntries.hasNext()) {
            entry = (LogEntry) logEntries.next();
            WGUpdateLog newLog = null;
            WGUpdateLog oldLog = null;
            Date currentTime = null;
            if (entry.getTarget() != null && !entry.getTarget().equals("#UNKNOWN#")) {
                newLog = readUpdateLog(entry);
                wgLogs.add(newLog);

                List logsList = (List) wgLogsByTarget.get(entry.getTarget());
                if (logsList == null) {
                    logsList = new ArrayList();
                    wgLogsByTarget.put(entry.getTarget(), logsList);
                }
                logsList.add(newLog);
            }
        }

        // Second pass for CS version < 5 to workaround some weaknesses of the CS3/4 history log
        if (_ddlVersion < WGDatabase.CSVERSION_WGA5) {

            // Determine conflicting log entries, where update and delete is done on the same time and the same document
            Iterator wgLogsByTargetIt = wgLogsByTarget.values().iterator();
            while (wgLogsByTargetIt.hasNext()) {
                List logs = (List) wgLogsByTargetIt.next();
                WGUtils.sortByProperty(logs, "date");
                Iterator logsIt = logs.iterator();
                Date lastTime = null;
                List<WGUpdateLog> logsAtSameTime = new ArrayList();
                while (logsIt.hasNext()) {
                    WGUpdateLog log = (WGUpdateLog) logsIt.next();
                    if (log.getDate().equals(lastTime)) {
                        logsAtSameTime.add(log);
                    } else {
                        resolveLogConflicts(wgLogs, logsAtSameTime);
                        logsAtSameTime.clear();
                    }
                    lastTime = log.getDate();
                }
            }

            // Order logentries that have the same time in an order that assures dependency documents are created before their dependent documents
            Collections.sort(wgLogs, new DocumentDependencyComparator());

        }

        return wgLogs;
    } catch (HibernateException e) {
        throw new WGBackendException("Unable to retrieve updated documents", e);
    }

}