Example usage for org.hibernate.type StandardBasicTypes LONG

List of usage examples for org.hibernate.type StandardBasicTypes LONG

Introduction

In this page you can find the example usage for org.hibernate.type StandardBasicTypes LONG.

Prototype

LongType LONG

To view the source code for org.hibernate.type StandardBasicTypes LONG.

Click Source Link

Document

The standard Hibernate type for mapping Long to JDBC java.sql.Types#BIGINT BIGINT .

Usage

From source file:edu.psu.iam.cpr.core.database.tables.UseridTable.java

License:Apache License

/**
 * This routine is used to determine if the passed in userid is valid.
 * @param db contains a reference to the database handle.
 * @param userid contains the userid to valid.
 * @return will return true if the userid is valid, otherwise it will return false.
 */// www  .j a v  a2 s  .  c om
public boolean isUseridValid(final Database db, final String userid) {

    final Session session = db.getSession();
    // Verify that the userid does not contain spaces.
    if (userid.contains(" ")) {
        return false;
    }
    // Verify that the userid only contains letters, numbers, $ and underscore.
    if (!userid.matches("^[a-zA-Z0-9$_]+$")) {
        return false;
    }

    // Obtain the character portion of the userid.
    final String charPart = getCharacterPart(userid);

    // Verify that the userid does not exist in the bad prefixes table.
    String sqlQuery = "SELECT char_part FROM {h-schema}bad_prefixes WHERE char_part = :char_part_in";
    SQLQuery query = session.createSQLQuery(sqlQuery);
    query.setParameter("char_part_in", charPart);
    query.addScalar("char_part", StandardBasicTypes.STRING);
    if (query.list().size() > 0) {
        return false;
    }

    // Verify that the userid does not already exist.
    sqlQuery = "SELECT person_id FROM {h-schema}userid WHERE userid = :userid_in";
    query = session.createSQLQuery(sqlQuery);
    query.setParameter("userid_in", userid);
    query.addScalar("person_id", StandardBasicTypes.LONG);
    if (query.list().size() > 0) {
        return false;
    }

    return true;
}

From source file:edu.psu.iam.cpr.core.messaging.ServiceProvisionerQueue.java

License:Apache License

/**
 * This routine is used to obtain a list of service providers and their respective queues for a particular web service.
 * @param db contains a database connection.
 * @param webService contains the web server to do the query for.
 * @return will return an ArrayList of service provider information.
 *///from w  w  w.  jav a2 s.  c o m
public static ArrayList<ServiceProvisionerQueue> getServiceProvisionerQueues(Database db, String webService) {

    final ArrayList<ServiceProvisionerQueue> results = new ArrayList<ServiceProvisionerQueue>();
    final Session session = db.getSession();

    final StringBuilder sb = new StringBuilder(BUFFER_SIZE);
    sb.append("SELECT service_provisioner_key, service_provisioner, web_service_key, web_service, ");
    sb.append("service_provisioner_queue FROM v_sp_notification WHERE web_service=:web_service ");

    final SQLQuery query = session.createSQLQuery(sb.toString());
    query.setParameter("web_service", webService);
    query.addScalar("service_provisioner_key", StandardBasicTypes.LONG);
    query.addScalar("service_provisioner", StandardBasicTypes.STRING);
    query.addScalar("web_service_key", StandardBasicTypes.LONG);
    query.addScalar("web_service", StandardBasicTypes.STRING);
    query.addScalar("service_provisioner_queue", StandardBasicTypes.STRING);
    final Iterator<?> it = query.list().iterator();

    while (it.hasNext()) {
        Object res[] = (Object[]) it.next();
        results.add(new ServiceProvisionerQueue((Long) res[SP_KEY], (String) res[SP_NAME],
                (Long) res[WEB_SERVICE_KEY], (String) res[WEB_SERVICE], (String) res[SP_QUEUE]));
    }

    return results;
}

From source file:gov.opm.scrd.entities.common.OPMPostgreSQLDialect.java

License:Apache License

/**
 * Default constructor.
 */
public OPMPostgreSQLDialect() {
    super();
    registerHibernateType(Types.BIGINT, StandardBasicTypes.LONG.getName());
}

From source file:gov.utah.dts.det.ccl.dao.impl.FacilityDaoImpl.java

License:Open Source License

@Override
public List<UserCaseloadCount> getUserCaseloadCounts() {
    Session session = (Session) em.getDelegate();
    SQLQuery query = session.createSQLQuery(CASELOAD_COUNT_QUERY);
    query.addScalar("id", StandardBasicTypes.LONG);
    query.addScalar("name", StandardBasicTypes.STRING);
    query.addScalar("roleType", StandardBasicTypes.STRING);
    query.addScalar("active", StandardBasicTypes.YES_NO);
    query.addScalar("count", StandardBasicTypes.LONG);
    query.setResultTransformer(Transformers.aliasToBean(UserCaseloadCount.class));
    return (List<UserCaseloadCount>) query.list();
}

From source file:junit.googlecode.genericdao.dao.hibernate.BaseDAOTest.java

License:Apache License

@Test
public void testProxyIssues() throws HibernateException, SecurityException, NoSuchMethodException {
    initDB();//from   www  .jav a 2 s . c  o  m
    Address address = papaA.getHome().getAddress();
    try {
        Serializable id = address.getId();

        // When working with 2 different session, the session.contains(entity) returns false
        // see in _exists(Object entity) in HibernateBaseDAO
        SessionImplementor openSession = (SessionImplementor) sessionFactory.openSession();

        Address proxy = (Address) JavassistLazyInitializer.getProxy(Address.class.getName(), Address.class,
                new Class[] { HibernateProxy.class }, Address.class.getMethod("getId"),
                Address.class.getMethod("setId", Long.class),
                new AnyType(StandardBasicTypes.LONG, StandardBasicTypes.SERIALIZABLE), id, openSession);

        // If this is not working properly, this will throw an error
        target.saveOrUpdateIsNew(proxy);

        //So will this
        Address address2 = target.get(proxy.getClass(), id);

        assertEquals("update on the proxy should work ", proxy.getCity(), address2.getCity());

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

}

From source file:ke.co.mspace.nonsmppmanager.service.SMSOutServiceImpl.java

@Override
public Map<String, Object> smsOutGroupBy(String user, String startDate, String endDate) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.getTransaction().begin();/* w  ww  . j  a  v  a 2  s . co m*/
    Criteria criteria = session.createCriteria(SMSOut.class);

    /*
     * This is where the report is going to come from
     * projectionList.add(Projections.sqlGroupProjection("YEAR(time_submitted) as yearSubmitted, MONTHNAME(STR_TO_DATE(MONTH(time_submitted), '%m')) as monthSubmitted, time_submitted as timeSubmitted", "timeSubmitted", new String[] { "monthSubmitted", "timeSubmitted", "yearSubmitted" }, new Type[] { StandardBasicTypes.STRING }));
     */
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.sqlGroupProjection(
            "YEAR(time_submitted) as yearSubmitted, MONTHNAME(STR_TO_DATE(MONTH(time_submitted), '%m')) as timeSubmitted",
            "yearSubmitted, timeSubmitted", new String[] { "yearSubmitted", "timeSubmitted" },
            new Type[] { StandardBasicTypes.LONG, StandardBasicTypes.STRING }));

    projectionList.add(Projections.rowCount());

    criteria.setProjection(projectionList); //This is added
    criteria.add(Restrictions.eq("user", user));
    criteria.addOrder(Order.asc("timeSubmitted"));
    criteria.add(Restrictions.between("timeSubmitted", startDate, endDate));

    List<Object[]> results = criteria.list();

    for (Object[] aResult : results) {
        System.out.println("the Object: " + Arrays.deepToString(aResult));
        System.out.println("Year : " + aResult[0] + " Month : " + aResult[1] + " No. Sent : " + aResult[2]);
    }

    Map<String, Object> mapResult = new HashMap<>();
    mapResult.put("result", results);
    mapResult.put("noSMS", 20);

    session.getTransaction().commit();
    return mapResult;
}

From source file:ke.co.mspace.nonsmppmanager.service.SMSOutServiceImpl.java

@Override
public Map<String, String> smsOutGroupByUser(String startDate, String endDate) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.getTransaction().begin();/*from w  w  w  .j  a va 2 s.  c o m*/
    Criteria criteria = session.createCriteria(SMSOut.class);

    Calendar startAnotherDate = null;
    Calendar endAnotherDate = null;
    try {
        startAnotherDate = stringToCalendar(startDate);
        endAnotherDate = stringToCalendar(endDate);
    } catch (ParseException ex) {
        Logger.getLogger(SMSOutServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    /*
     * This is where the report is going to come from
     * projectionList.add(Projections.sqlGroupProjection("YEAR(time_submitted) as yearSubmitted, MONTHNAME(STR_TO_DATE(MONTH(time_submitted), '%m')) as monthSubmitted, time_submitted as timeSubmitted", "timeSubmitted", new String[] { "monthSubmitted", "timeSubmitted", "yearSubmitted" }, new Type[] { StandardBasicTypes.STRING }));
     */
    ProjectionList projectionList = Projections.projectionList();
    projectionList.add(Projections.sqlGroupProjection(
            "YEAR(time_submitted) as yearSubmitted, MONTHNAME(STR_TO_DATE(MONTH(time_submitted), '%m')) as timeSubmitted, user as userName",
            "yearSubmitted, timeSubmitted, userName",
            new String[] { "yearSubmitted", "timeSubmitted", "userName" },
            new Type[] { StandardBasicTypes.LONG, StandardBasicTypes.STRING, StandardBasicTypes.STRING }));
    projectionList.add(Projections.rowCount());
    criteria.setProjection(projectionList);
    criteria.addOrder(Order.asc("timeSubmitted"));
    criteria.add(Restrictions.between("timeSubmitted", startDate, endDate));

    List<Object[]> results = criteria.list();
    Map<String, Integer> json = new LinkedHashMap<>();
    Set<String> months = new LinkedHashSet<>();
    Set<String> users = new LinkedHashSet<>();

    while (startAnotherDate.before(endAnotherDate)) {
        String month = startAnotherDate.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
        int year = startAnotherDate.get(Calendar.YEAR);
        for (Object[] aResult : results) {
            json.put(year + "-" + month + "-" + aResult[2], 0);
            months.add(aResult[0] + "-" + aResult[1]);
            users.add(String.valueOf(aResult[2]));
        }

        startAnotherDate.add(Calendar.MONTH, 1);
    }

    String madeUp = null;
    for (String aString : json.keySet()) {
        for (Object[] aResult : results) {
            madeUp = aResult[0] + "-" + aResult[1] + "-" + aResult[2];
            if (aString.equals(madeUp)) {
                json.put(aString, Integer.parseInt(String.valueOf(aResult[3])));
            }
        }

    }
    StringBuilder builder = new StringBuilder();

    for (String aMonth : months) {
        builder.append("[");
        builder.append('"');
        builder.append(aMonth.substring(0, 8));
        builder.append('"');
        builder.append(',');
        for (String aString : json.keySet()) {
            if (aString.contains(aMonth)) {

                builder.append(json.get(aString));
                builder.append(",");
            }

        }
        builder.append("]");
        if (builder.length() > 0) {

            if (builder.charAt(builder.lastIndexOf("]") - 1) == ',') {
                builder.deleteCharAt(builder.lastIndexOf("]") - 1);
            }
        }
        builder.append(",");
    }
    if (builder.length() > 0) {

        builder.deleteCharAt(builder.lastIndexOf(","));

    }
    StringBuilder userBuilder = new StringBuilder();
    userBuilder.append("[");
    for (String aUser : users) {

        userBuilder.append('"');
        userBuilder.append(aUser);
        userBuilder.append('"');
        userBuilder.append(',');
    }
    userBuilder.append(']');
    if (userBuilder.length() > 0) {

        if (userBuilder.charAt(userBuilder.lastIndexOf("]") - 1) == ',') {
            userBuilder.deleteCharAt(userBuilder.lastIndexOf("]") - 1);
        }
    }

    System.out.println("A new builder : " + builder.toString());
    System.out.println("The Users : " + userBuilder.toString());

    Map<String, String> mapResult = new HashMap<>();
    mapResult.put("data", builder.toString());
    mapResult.put("users", userBuilder.toString());

    session.getTransaction().commit();
    return mapResult;
}

From source file:net.webpasswordsafe.server.dao.PasswordDAOHibernate.java

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public List<Password> findPasswordByFuzzySearch(String query, User user, boolean activeOnly,
        Collection<Tag> tags, Match tagMatch) {
    //kludge to not use ilike on text column if MSSQL
    boolean isMSSQL = ((SessionFactoryImpl) getSessionFactory()).getDialect().toString().contains("SQLServer");
    Criteria crit = getSession().createCriteria(getPersistentClass());
    crit.setFetchMode("tags", FetchMode.JOIN);
    crit.add(Restrictions.or(//from w w w. jav  a  2 s.c  om
            Restrictions.or(Restrictions.ilike("name", query, MatchMode.ANYWHERE),
                    Restrictions.ilike("username", query, MatchMode.ANYWHERE)),
            isMSSQL ? Restrictions.like("notes", query, MatchMode.ANYWHERE)
                    : Restrictions.ilike("notes", query, MatchMode.ANYWHERE)));
    if (activeOnly) {
        crit.add(Restrictions.eq("active", true));
    }
    Criterion tagsCriterion = null;
    for (Tag tag : tags) {
        Criterion tc = Restrictions.sqlRestriction(
                "? in (select tag_id from password_tags where password_id = {alias}.id)", tag.getId(),
                StandardBasicTypes.LONG);
        if (null == tagsCriterion) {
            tagsCriterion = tc;
        } else {
            tagsCriterion = tagMatch.equals(Match.AND) ? Restrictions.and(tagsCriterion, tc)
                    : Restrictions.or(tagsCriterion, tc);
        }
    }
    if (tagsCriterion != null)
        crit.add(tagsCriterion);
    crit.createAlias("permissions", "pm");
    crit.add(Restrictions.in("pm.accessLevel",
            new String[] { AccessLevel.READ.name(), AccessLevel.WRITE.name(), AccessLevel.GRANT.name() }));
    if (!authorizer.isAuthorized(user, Function.BYPASS_PASSWORD_PERMISSIONS.name())) {
        DetachedCriteria groupQuery = DetachedCriteria.forClass(Group.class);
        groupQuery.setProjection(Projections.id());
        groupQuery.createCriteria("users", "u").add(Restrictions.eq("u.id", user.getId()));
        crit.add(Restrictions.or(Restrictions.eq("pm.subject", user),
                Subqueries.propertyIn("pm.subject", groupQuery)));
    }
    crit.addOrder(Order.asc("name"));
    crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
    return crit.list();
}

From source file:nl.strohalm.cyclos.dao.accounts.AccountDAOImpl.java

License:Open Source License

public Iterator<MemberTransactionSummaryVO> membersTransactionSummaryReport(
        final Collection<MemberGroup> memberGroups, final PaymentFilter paymentFilter, final Period period,
        final boolean credits, final MemberResultDisplay order) {
    final Map<String, Object> parameters = new HashMap<String, Object>();
    final StringBuilder sql = new StringBuilder();

    // Get the transfer types ids
    final List<Long> ttIds = paymentFilter == null ? null
            : Arrays.asList(EntityHelper.toIds(paymentFilter.getTransferTypes()));

    // Get the member group ids
    List<Long> groupIds = null;
    if (CollectionUtils.isNotEmpty(memberGroups)) {
        groupIds = Arrays.asList(EntityHelper.toIds(memberGroups));
    }//from   www .  j  a  v  a 2s .  c  o  m

    // Get the period
    final QueryParameter beginParameter = HibernateHelper.getBeginParameter(period);
    final QueryParameter endParameter = HibernateHelper.getEndParameter(period);

    // Set the parameters
    final boolean useGroups = CollectionUtils.isNotEmpty(groupIds);
    final boolean useTT = CollectionUtils.isNotEmpty(ttIds);
    if (useGroups) {
        parameters.put("groupIds", groupIds);
    }
    if (useTT) {
        parameters.put("ttIds", ttIds);
    }
    if (beginParameter != null) {
        parameters.put("beginDate", beginParameter.getValue());
    }
    if (endParameter != null) {
        parameters.put("endDate", endParameter.getValue());
    }
    parameters.put("processed", Payment.Status.PROCESSED.getValue());

    // Create the SQL query
    sql.append(" select member_id, sum(count) as count, sum(amount) as amount");
    sql.append(" from (");
    appendMembersTransactionsSummaryReportSqlPart(sql, useGroups, useTT, beginParameter, endParameter, credits,
            true);
    sql.append(" union");
    appendMembersTransactionsSummaryReportSqlPart(sql, useGroups, useTT, beginParameter, endParameter, credits,
            false);
    sql.append(" ) ts");
    sql.append(" group by member_id");
    sql.append(" order by ").append(order == MemberResultDisplay.NAME ? "member_name, member_id" : "username");

    final SQLQuery query = getSession().createSQLQuery(sql.toString());
    query.addScalar("member_id", StandardBasicTypes.LONG);
    query.addScalar("count", StandardBasicTypes.INTEGER);
    query.addScalar("amount", StandardBasicTypes.BIG_DECIMAL);
    getHibernateQueryHandler().setQueryParameters(query, parameters);

    final Transformer<Object[], MemberTransactionSummaryVO> transformer = new Transformer<Object[], MemberTransactionSummaryVO>() {
        public MemberTransactionSummaryVO transform(final Object[] input) {
            final MemberTransactionSummaryVO vo = new MemberTransactionSummaryVO();
            vo.setMemberId((Long) input[0]);
            vo.setCount((Integer) input[1]);
            vo.setAmount((BigDecimal) input[2]);
            return vo;
        }
    };

    return new ScrollableResultsIterator<MemberTransactionSummaryVO>(query, transformer);
}

From source file:nl.strohalm.cyclos.dao.members.ReferenceDAOImpl.java

License:Open Source License

public List<PaymentAwaitingFeedbackDTO> searchPaymentsAwaitingFeedback(
        final PaymentsAwaitingFeedbackQuery query) {

    final ResultType resultType = query.getResultType();
    final PageParameters pageParameters = query.getPageParameters();
    final boolean countOnly = resultType == ResultType.PAGE && pageParameters != null
            && pageParameters.getMaxResults() == 0;

    // There are 2 tables which contains payments that can have feedback: transfers and scheduled payments
    // As we need an union, we need a native SQL

    final Member member = query.getMember();
    Boolean expired = query.getExpired();

    final StringBuilder sql = new StringBuilder();
    sql.append(" select ");
    if (countOnly) {
        sql.append(" count(*) as row_count");
    } else {/*from  w  w w.  j  av  a2s.  c  om*/
        sql.append(" * ");
    }
    sql.append(" from ( ");
    {
        sql.append(
                " select t.id, t.type_id as transferTypeId, false as scheduled, t.date, t.amount, tm.id as memberId, tm.name as memberName, ta.owner_name as memberUsername");
        sql.append(
                " from transfers t inner join transfer_types tt on t.type_id = tt.id inner join accounts ta on t.to_account_id = ta.id inner join members tm on ta.member_id = tm.id");
        if (member != null) {
            sql.append(" inner join accounts a on t.from_account_id = a.id");
        }
        sql.append(" left join refs tf on tf.transfer_id = t.id");
        sql.append(" where tt.requires_feedback = true");
        sql.append(" and t.date >= tt.feedback_enabled_since");
        sql.append(" and t.parent_id is null");
        sql.append(" and t.chargeback_of_id is null");
        sql.append(" and t.scheduled_payment_id is null");
        sql.append(" and t.process_date is not null");
        if (expired != null) {
            sql.append(" and t.feedback_deadline " + (expired ? "<" : ">=") + " now()");
        }
        sql.append(" and tf.id is null");
        if (member != null) {
            sql.append(" and a.member_id = :memberId");
        }

        sql.append(" union ");

        sql.append(" select sp.id, sp.type_id, true, sp.date, sp.amount, tm.id, tm.name, ta.owner_name");
        sql.append(
                " from scheduled_payments sp inner join transfer_types tt on sp.type_id = tt.id inner join accounts ta on sp.to_account_id = ta.id inner join members tm on ta.member_id = tm.id");
        if (member != null) {
            sql.append(" inner join accounts a on sp.from_account_id = a.id");
        }
        sql.append(" left join refs tf on tf.scheduled_payment_id = sp.id");
        sql.append(" where tt.requires_feedback = true");
        if (expired != null) {
            sql.append(" and sp.feedback_deadline " + (expired ? "<" : ">=") + " now()");
        }
        sql.append(" and sp.date >= tt.feedback_enabled_since");
        sql.append(" and tf.id is null");
        if (member != null) {
            sql.append(" and a.member_id = :memberId");
        }
    }
    sql.append(") as awaiting ");
    if (!countOnly) {
        sql.append("order by date");
    }

    SQLQuery sqlQuery = getSession().createSQLQuery(sql.toString());
    if (member != null) {
        sqlQuery.setLong("memberId", member.getId());
    }
    if (countOnly) {
        // Handle the special case for count only
        sqlQuery.addScalar("row_count", StandardBasicTypes.INTEGER);
        int count = ((Number) sqlQuery.uniqueResult()).intValue();
        return new PageImpl<PaymentAwaitingFeedbackDTO>(pageParameters, count,
                Collections.<PaymentAwaitingFeedbackDTO>emptyList());
    } else {
        // Execute the search
        sqlQuery.addScalar("id", StandardBasicTypes.LONG);
        sqlQuery.addScalar("transferTypeId", StandardBasicTypes.LONG);
        sqlQuery.addScalar("scheduled", StandardBasicTypes.BOOLEAN);
        sqlQuery.addScalar("date", StandardBasicTypes.CALENDAR);
        sqlQuery.addScalar("amount", StandardBasicTypes.BIG_DECIMAL);
        sqlQuery.addScalar("memberId", StandardBasicTypes.LONG);
        sqlQuery.addScalar("memberName", StandardBasicTypes.STRING);
        sqlQuery.addScalar("memberUsername", StandardBasicTypes.STRING);
        getHibernateQueryHandler().applyPageParameters(pageParameters, sqlQuery);

        // We'll always use an iterator, even if it is for later adding it to a list
        Iterator<PaymentAwaitingFeedbackDTO> iterator = new ScrollableResultsIterator<PaymentAwaitingFeedbackDTO>(
                sqlQuery, new Transformer<Object[], PaymentAwaitingFeedbackDTO>() {
                    public PaymentAwaitingFeedbackDTO transform(final Object[] input) {
                        PaymentAwaitingFeedbackDTO dto = new PaymentAwaitingFeedbackDTO();
                        dto.setId((Long) input[0]);
                        dto.setTransferTypeId((Long) input[1]);
                        dto.setScheduled(Boolean.TRUE.equals(input[2]));
                        dto.setDate((Calendar) input[3]);
                        dto.setAmount((BigDecimal) input[4]);
                        dto.setMemberId((Long) input[5]);
                        dto.setMemberName((String) input[6]);
                        dto.setMemberUsername((String) input[7]);

                        TransferType transferType = (TransferType) getSession().load(TransferType.class,
                                dto.getTransferTypeId());
                        dto.setCurrency(getFetchDao().fetch(transferType.getCurrency()));

                        return dto;
                    }
                });
        if (resultType == ResultType.ITERATOR) {
            return new IteratorListImpl<PaymentAwaitingFeedbackDTO>(iterator);
        } else {
            List<PaymentAwaitingFeedbackDTO> list = new ArrayList<PaymentAwaitingFeedbackDTO>();
            CollectionUtils.addAll(list, iterator);
            DataIteratorHelper.close(iterator);

            if (resultType == ResultType.PAGE) {
                // For page, we need another search for the total count
                query.setPageForCount();
                int totalCount = PageHelper.getTotalCount(searchPaymentsAwaitingFeedback(query));

                return new PageImpl<PaymentAwaitingFeedbackDTO>(pageParameters, totalCount, list);
            } else {
                return list;
            }
        }
    }
}