Java Code Examples for org.hibernate.type.StringType

The following examples show how to use org.hibernate.type.StringType. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test
public void test_sql_hibernate_query_scalar_explicit_result_set_example() {
  doInJPA(this::entityManagerFactory, entityManager -> {
    Session session = entityManager.unwrap(Session.class);
    //tag::sql-hibernate-scalar-query-explicit-result-set-example[]
    List<Object[]> persons = session.createNativeQuery(
        "SELECT * FROM Person")
        .addScalar("id", LongType.INSTANCE)
        .addScalar("name", StringType.INSTANCE)
        .list();

    for (Object[] person : persons) {
      Long id = (Long) person[0];
      String name = (String) person[1];
    }
    //end::sql-hibernate-scalar-query-explicit-result-set-example[]
    assertEquals(3, persons.size());
  });
}
 
Example 2
private List<SakaiPerson> listSakaiPersons(final Collection<String> userIds, final Type recordType)
{
	final HibernateCallback hcb = new HibernateCallback()
	{
		public Object doInHibernate(Session session) throws HibernateException
		{
			Query q = session.getNamedQuery(HQL_FIND_SAKAI_PERSONS_BY_AGENTS_AND_TYPE);
			q.setParameterList(AGENT_UUID_COLLECTION, userIds);
			q.setParameter(TYPE_UUID, recordType.getUuid(), StringType.INSTANCE);
			// q.setCacheable(false);
			return q.list();
		}
	};
	List hb =  (List) getHibernateTemplate().execute(hcb);
	if (photoService.overRidesDefault()) {
		return getDiskPhotosForList(hb);
	} else {
		return hb;
	}
}
 
Example 3
/**
 * helper method to get messages by type
 * @param typeUuid
 * @return message list
 */
public List getMessagesByType(final String typeUuid, final String orderField,
    final String order)
{

  if (log.isDebugEnabled())
  {
    log.debug("getMessagesByType(typeUuid:" + typeUuid + ", orderField: "
        + orderField + ", order:" + order + ")");
  }

  HibernateCallback<List> hcb = session -> {
    Query q = session.getNamedQuery(QUERY_MESSAGES_BY_USER_TYPE_AND_CONTEXT);
    Query qOrdered = session.createQuery(q.getQueryString() + " order by "
        + orderField + " " + order);

    qOrdered.setParameter("userId", getCurrentUser(), StringType.INSTANCE);
    qOrdered.setParameter("typeUuid", typeUuid, StringType.INSTANCE);
    qOrdered.setParameter("contextId", getContextId(), StringType.INSTANCE);
    return qOrdered.list();
  };

  return getHibernateTemplate().execute(hcb);
}
 
Example 4
private List initializeMessageCounts(final String userId, final String contextId)
{
  if (log.isDebugEnabled())
  {
    log.debug("initializeMessageCounts executing");
  }

  HibernateCallback<List> hcb = session -> {
    Query q = session.getNamedQuery(QUERY_AGGREGATE_COUNT);
    q.setParameter("contextId", contextId, StringType.INSTANCE);
    q.setParameter("userId", userId, StringType.INSTANCE);
    return q.list();
  };
      
  return getHibernateTemplate().execute(hcb);
}
 
Example 5
/**
 * FOR SYNOPTIC TOOL:
 * 	helper method to get messages by type
 * 	needed to pass contextId since could be in MyWorkspace
 * 
 * @param typeUuid
 * 			The type of forum it is (Private or Topic)
 * @param contextId
 * 			The site id whose messages are needed
 * 
 * @return message list
 */
public List getMessagesByTypeByContext(final String typeUuid, final String contextId)
{

  if (log.isDebugEnabled())
  {
    log.debug("getMessagesByTypeForASite(typeUuid:" + typeUuid + ")");
  }

  HibernateCallback<List> hcb = session -> {
    Query q = session.getNamedQuery(QUERY_MESSAGES_BY_USER_TYPE_AND_CONTEXT);

    q.setParameter("userId", getCurrentUser(), StringType.INSTANCE);
    q.setParameter("typeUuid", typeUuid, StringType.INSTANCE);
    q.setParameter("contextId", contextId, StringType.INSTANCE);
    return q.list();
  };

  return getHibernateTemplate().execute(hcb);
}
 
Example 6
public UnreadStatus findUnreadStatusByUserId(final Long topicId, final Long messageId, final String userId){
	if (messageId == null || topicId == null || userId == null) {
        log.error("findUnreadStatusByUserId failed with topicId: " + topicId + ", messageId: " + messageId
        		+ ", userId: " + userId);
        throw new IllegalArgumentException("Null Argument");
    }

    log.debug("findUnreadStatus executing with topicId: " + topicId + ", messageId: " + messageId);

    HibernateCallback<UnreadStatus> hcb = session -> {
        Query q = session.getNamedQuery(QUERY_UNREAD_STATUS);
        q.setParameter("topicId", topicId, LongType.INSTANCE);
        q.setParameter("messageId", messageId, LongType.INSTANCE);
        q.setParameter("userId", userId, StringType.INSTANCE);
        return (UnreadStatus) q.uniqueResult();
    };

    return getHibernateTemplate().execute(hcb);
}
 
Example 7
public List<UserStatistics> findAuthoredStatsForStudentByForumId(final String studentId, final Long topicId) {
	if (log.isDebugEnabled()) log.debug("findAuthoredStatsForStudentByForumId()");

	HibernateCallback<List<Object[]>> hcb = session -> {
        Query q = session.getNamedQuery("findAuthoredStatsForStudentByForumId");
        q.setParameter("forumId", topicId, LongType.INSTANCE);
        q.setParameter("userId", studentId, StringType.INSTANCE);
        return q.list();
    };
	List<UserStatistics> returnList = new ArrayList<UserStatistics>();
	List<Object[]> results = getHibernateTemplate().execute(hcb);
	for(Object[] result : results){
		UserStatistics stat = new UserStatistics((String) result[0], (String) result[1], (Date) result[2], (String) result[3], 
				((Integer) result[4]).toString(), ((Integer) result[5]).toString(), ((Integer) result[6]).toString(), studentId);
		returnList.add(stat);
	}
	return returnList;
}
 
Example 8
Source Project: sakai   Source File: RankManagerImpl.java    License: Educational Community License v2.0 6 votes vote down vote up
public List getRankList(final String contextId) {
    if (log.isDebugEnabled()) {
        log.debug("getRank(contextId: " + contextId + ")");
    }
    if (contextId == null) {
        throw new IllegalArgumentException("Null Argument");
    }
    if (!isRanksEnabled())
    {
        return new ArrayList();
    }
    HibernateCallback<List> hcb = session -> {
        Query q = session.getNamedQuery(QUERY_BY_CONTEXT_ID);
        q.setParameter("contextId", contextId, StringType.INSTANCE);
        return q.list();
    };

    return getHibernateTemplate().execute(hcb);
}
 
Example 9
@Override
@Transactional(readOnly = true)
public String fetchAssignmentContent(String contentId) {
    try {
        String xml = (String) sessionFactory.getCurrentSession()
                .createSQLQuery("SELECT XML FROM ASSIGNMENT_CONTENT WHERE CONTENT_ID = :id")
                .addScalar("XML", StringType.INSTANCE)
                .setParameter("id", contentId, StringType.INSTANCE)
                .uniqueResult();

        return xml;
    } catch (Exception e) {
        log.warn("could not query table ASSIGNMENT_CONTENT for assignment content {}, {}", contentId, e.getMessage());
    }
    return null;
}
 
Example 10
public List getMessagesByTypeByContext(final String typeUuid, final String contextId, final String userId, final String orderField,
     final String order){
  if (log.isDebugEnabled())
  {
    log.debug("getMessagesByTypeForASite(typeUuid:" + typeUuid + ")");
  }

  HibernateCallback<List> hcb = session -> {
    Query q = session.getNamedQuery(QUERY_MESSAGES_BY_USER_TYPE_AND_CONTEXT);
    Query qOrdered = session.createQuery(q.getQueryString() + " order by "
            + orderField + " " + order);
    qOrdered.setParameter("userId", userId, StringType.INSTANCE);
    qOrdered.setParameter("typeUuid", typeUuid, StringType.INSTANCE);
    qOrdered.setParameter("contextId", contextId, StringType.INSTANCE);
    return qOrdered.list();
  };

  return getHibernateTemplate().execute(hcb);
}
 
Example 11
public List<UserStatistics> findAuthoredStatsForStudent(final String studentId) {
  if (log.isDebugEnabled()) log.debug("findAuthoredStatsForStudent()");
  
  HibernateCallback<List<Object[]>> hcb = session -> {
      Query q = session.getNamedQuery("findAuthoredStatsForStudent");
      q.setParameter("contextId", getContextId(), StringType.INSTANCE);
      q.setParameter("userId", studentId, StringType.INSTANCE);
      return q.list();
  };
  List<UserStatistics> returnList = new ArrayList<UserStatistics>();
  List<Object[]> results = getHibernateTemplate().execute(hcb);
  for(Object[] result : results){
	  UserStatistics stat = new UserStatistics((String) result[0], (String) result[1], (Date) result[2], (String) result[3], 
			  ((Integer) result[4]).toString(), ((Integer) result[5]).toString(), ((Integer) result[6]).toString(), studentId);
	  returnList.add(stat);
  }
  return returnList;
}
 
Example 12
Source Project: dkpro-jwpl   Source File: Wikipedia.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the page ids for a given title with case insensitive matching.<br>
 *
 *
 * @param title The title of the page.
 * @return The ids of the pages with the given title.
 * @throws WikiApiException Thrown if errors occurred.
 */
public List<Integer> getPageIdsCaseInsensitive(String title) throws WikiApiException {
    title = title.toLowerCase();
    title = title.replaceAll(" ", "_");

    Session session = this.__getHibernateSession();
    session.beginTransaction();
    Iterator results = session.createQuery(
    "select p.pageID from PageMapLine as p where lower(p.name) = :pName").setParameter("pName", title, StringType.INSTANCE).list().iterator();

    session.getTransaction().commit();

    if(!results.hasNext()){
        throw new WikiPageNotFoundException();
    }
    List<Integer> resultList = new LinkedList<Integer>();
    while(results.hasNext()){
        resultList.add((Integer)results.next());
    }
    return resultList;
}
 
Example 13
Source Project: dkpro-jwpl   Source File: Wikipedia.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return an iterable containing all archived discussion pages for
 * the given article page. The most recent discussion page is not included.
 * The most recent discussion page can be obtained with {@link #getDiscussionPage(Page)}.
 * <br>
 * The provided page Object must not be a discussion page itself! If it is
 * a discussion page, is returned unchanged.
 *
 * @param articlePage the article page for which a discussion archives should be retrieved
 * @return An iterable with the discussion archive page objects for the given article page object
 * @throws WikiApiException If no page or redirect with this title exists or title could not be properly parsed.
 */
public Iterable<Page> getDiscussionArchives(Page articlePage) throws WikiApiException{
    String articleTitle = articlePage.getTitle().getWikiStyleTitle();
	if(!articleTitle.startsWith(WikiConstants.DISCUSSION_PREFIX)){
		articleTitle=WikiConstants.DISCUSSION_PREFIX+articleTitle;
	}

	Session session = this.__getHibernateSession();
    session.beginTransaction();

    List<Page> discussionArchives = new LinkedList<Page>();

    Query query = session.createQuery("SELECT pageID FROM PageMapLine where name like :name");
    query.setParameter("name", articleTitle+"/%", StringType.INSTANCE);
    Iterator results = query.list().iterator();

    session.getTransaction().commit();

    while (results.hasNext()) {
        int pageID = (Integer) results.next();
        discussionArchives.add(getPage(pageID));
    }

    return discussionArchives;

}
 
Example 14
@Override
@Transactional(readOnly = true)
public String fetchAssignmentContent(String contentId) {
    try {
        String xml = (String) sessionFactory.getCurrentSession()
                .createSQLQuery("SELECT XML FROM ASSIGNMENT_CONTENT WHERE CONTENT_ID = :id")
                .addScalar("XML", StringType.INSTANCE)
                .setParameter("id", contentId, StringType.INSTANCE)
                .uniqueResult();

        return xml;
    } catch (Exception e) {
        log.warn("could not query table ASSIGNMENT_CONTENT for assignment content {}, {}", contentId, e.getMessage());
    }
    return null;
}
 
Example 15
@Override
@Transactional(readOnly = true)
public List<String> fetchAssignmentSubmissions(String assignmentId) {
    try {
        List<String> list = sessionFactory.getCurrentSession()
                .createSQLQuery("SELECT XML FROM ASSIGNMENT_SUBMISSION WHERE CONTEXT = :id")
                .addScalar("XML", StringType.INSTANCE)
                .setParameter("id", assignmentId, StringType.INSTANCE)
                .list();

        return list;
    } catch (Exception e) {
        log.warn("could not query table ASSIGNMENT_SUBMISSION for submissions to migrate, {}", e.getMessage());
    }
    return Collections.emptyList();
}
 
Example 16
public List<UserStatistics> findAuthoredStatsForStudent(final String studentId) {
  if (log.isDebugEnabled()) log.debug("findAuthoredStatsForStudent()");
  
  HibernateCallback<List<Object[]>> hcb = session -> {
      Query q = session.getNamedQuery("findAuthoredStatsForStudent");
      q.setParameter("contextId", getContextId(), StringType.INSTANCE);
      q.setParameter("userId", studentId, StringType.INSTANCE);
      return q.list();
  };
  List<UserStatistics> returnList = new ArrayList<UserStatistics>();
  List<Object[]> results = getHibernateTemplate().execute(hcb);
  for(Object[] result : results){
	  UserStatistics stat = new UserStatistics((String) result[0], (String) result[1], (Date) result[2], (String) result[3], 
			  ((Integer) result[4]).toString(), ((Integer) result[5]).toString(), ((Integer) result[6]).toString(), studentId);
	  returnList.add(stat);
  }
  return returnList;
}
 
Example 17
public List<UserStatistics> findReadStatsForStudentByTopicId(final String studentId, final Long topicId) {
	if (log.isDebugEnabled()) log.debug("findReadStatsForStudentByTopicId()");

	HibernateCallback<List<Object[]>> hcb = session -> {
        Query q = session.getNamedQuery("findReadStatsForStudentByTopicId");
        q.setParameter("userId", studentId, StringType.INSTANCE);
        q.setParameter("topicId", topicId, LongType.INSTANCE);
        return q.list();
    };
    List<UserStatistics> returnList = new ArrayList<UserStatistics>();
    List<Object[]> results = getHibernateTemplate().execute(hcb);
    for(Object[] result : results){
  	  UserStatistics stat = new UserStatistics((String) result[0], (String) result[1], (Date) result[2], (String) result[3], 
  			  ((Integer) result[4]).toString(), ((Integer) result[5]).toString(), ((Integer) result[6]).toString(), studentId);
  	  returnList.add(stat);
    }
    return returnList;
}
 
Example 18
Source Project: sakai   Source File: ProfileDaoImpl.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public List<String> getRequestedConnectionUserIdsForUser(final String userId) {
			
	//get friends of this user [and map it automatically to the Friend object]
	//updated: now just returns a List of Strings
	final HibernateCallback<List<String>> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_FRIEND_REQUESTS_FOR_USER);
           q.setParameter(USER_UUID, userId, StringType.INSTANCE);
           q.setBoolean("false", Boolean.FALSE);
           //q.setResultTransformer(Transformers.aliasToBean(Friend.class));

           return q.list();
       };
  	
  	return getHibernateTemplate().execute(hcb);
}
 
Example 19
Source Project: sakai   Source File: ProfileDaoImpl.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public List<String> findSakaiPersonsByInterest(final String search, final boolean includeBusinessBio) {
	
	//get 
	final HibernateCallback<List<String>> hcb = session -> {
           Query q;
           if (false == includeBusinessBio) {
               q = session.getNamedQuery(QUERY_FIND_SAKAI_PERSONS_BY_INTEREST);
           } else {
               q = session.getNamedQuery(QUERY_FIND_SAKAI_PERSONS_BY_INTEREST_AND_BUSINESS_BIO);
           }
           q.setParameter(SEARCH, '%' + search + '%', StringType.INSTANCE);
           return q.list();
       };
  	
  	return getHibernateTemplate().execute(hcb);
}
 
Example 20
public List<UserStatistics> findReadStatsForStudent(final String studentId) {
  if (log.isDebugEnabled()) log.debug("findReadStatsForStudent()");
  
  HibernateCallback<List<Object[]>> hcb = session -> {
      Query q = session.getNamedQuery("findReadStatsForStudent");
      q.setParameter("contextId", getContextId(), StringType.INSTANCE);
      q.setParameter("userId", studentId, StringType.INSTANCE);
      return q.list();
  };
  List<UserStatistics> returnList = new ArrayList<UserStatistics>();
  List<Object[]> results = getHibernateTemplate().execute(hcb);
  for(Object[] result : results){
	  UserStatistics stat = new UserStatistics((String) result[0], (String) result[1], (Date) result[2], (String) result[3], 
			  ((Integer) result[4]).toString(), ((Integer) result[5]).toString(), ((Integer) result[6]).toString(), studentId);
	  returnList.add(stat);
  }
  return returnList;
}
 
Example 21
protected static boolean emptyStringToNull(Object entity, Serializable id,
        Object[] state, String[] propertyNames, Type[] types,
        boolean autoConvert) {

    boolean modified = false;

    for (int i = 0; i < types.length; i++) {
        // type is string (VARCHAR) and state is empty string
        if ((types[i] instanceof StringType) && "".equals(state[i])) {
            if (LOG.isEnabledFor(Level.WARN)) {
                LOG.warn("Object " + entity.getClass().getCanonicalName() +
                        " is setting empty string " + propertyNames[i]);
            }
            if (autoConvert) {
                state[i] = null;
                modified = true;
            }
        }
    }
    return modified;
}
 
Example 22
Source Project: sakai   Source File: RankManagerImpl.java    License: Educational Community License v2.0 6 votes vote down vote up
public List getRankList(final String contextId) {
    if (log.isDebugEnabled()) {
        log.debug("getRank(contextId: " + contextId + ")");
    }
    if (contextId == null) {
        throw new IllegalArgumentException("Null Argument");
    }
    if (!isRanksEnabled())
    {
        return new ArrayList();
    }
    HibernateCallback<List> hcb = session -> {
        Query q = session.getNamedQuery(QUERY_BY_CONTEXT_ID);
        q.setParameter("contextId", contextId, StringType.INSTANCE);
        return q.list();
    };

    return getHibernateTemplate().execute(hcb);
}
 
Example 23
public Area getAreaByContextIdAndTypeId(final String typeId) {
  log.debug("getAreaByContextIdAndTypeId executing for current user: " + getCurrentUser());
  HibernateCallback<Area> hcb = session -> {
      Query q = session.getNamedQuery("findAreaByContextIdAndTypeId");
      q.setParameter("contextId", getContextId(), StringType.INSTANCE);
      q.setParameter("typeId", typeId, StringType.INSTANCE);
      return (Area) q.uniqueResult();
  };

  return getHibernateTemplate().execute(hcb);
}
 
Example 24
@Test
public void test_hql_api_parameter_example() {
	doInJPA( this::entityManagerFactory, entityManager -> {
		Session session = entityManager.unwrap( Session.class );
		//tag::hql-api-parameter-example[]
		org.hibernate.query.Query query = session.createQuery(
			"select p " +
			"from Person p " +
			"where p.name like :name" )
		.setParameter( "name", "J%", StringType.INSTANCE );
		//end::hql-api-parameter-example[]
	});
}
 
Example 25
Source Project: sakai   Source File: ProfileDaoImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public List<GalleryImage> getGalleryImages(final String userId) {
	
	final HibernateCallback<List<GalleryImage>> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_GALLERY_IMAGE_RECORDS);
           q.setParameter(USER_UUID, userId, StringType.INSTANCE);
           return q.list();
       };
  	
  	return getHibernateTemplate().execute(hcb);
}
 
Example 26
Source Project: sakai   Source File: ProfileDaoImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public List<String> getThreadParticipants(final String threadId) {
	
	//get
	final HibernateCallback<List<String>> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_THREAD_PARTICIPANTS);
           q.setParameter(THREAD, threadId, StringType.INSTANCE);
           return q.list();
       };
  	
  	return getHibernateTemplate().execute(hcb);
}
 
Example 27
Source Project: sailfish-core   Source File: TimestampToString.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object nullSafeGet(ResultSet ps, String[] names, SessionImplementor s, Object owner)
		throws HibernateException, SQLException {
	String value = StringType.INSTANCE.nullSafeGet(ps, names[0], s);
	Date time = null;
	try {
		time = MessageRow.TIMESTAMP_FORMAT.get().parse(value);
	} catch (ParseException e) {
		logger.error(e.getMessage(), e);
	}
       return time != null ? new Timestamp(time.getTime()) : null;
}
 
Example 28
public void updateAllSiteTitles(final String siteId, final String siteTitle) {
	HibernateCallback<Integer> hcb = session -> {
           Query q = session.getNamedQuery(QUERY_UPDATE_ALL_SITE_TITLES);
           q.setParameter("siteTitle", siteTitle, StringType.INSTANCE);
           q.setParameter("siteId", siteId, StringType.INSTANCE);
           return q.executeUpdate();
       };

	getHibernateTemplate().execute(hcb);
}
 
Example 29
Source Project: unitime   Source File: EventFilterBackend.java    License: Apache License 2.0 5 votes vote down vote up
public org.hibernate.Query setParams(org.hibernate.Query query, Collection<String> excludeOption) {
	for (Map.Entry<String, Map<String, Object>> entry: iParams.entrySet()) {
		if (excludeOption != null && excludeOption.contains(entry.getKey())) continue;
		for (Map.Entry<String, Object> param: entry.getValue().entrySet()) {
			if (param.getValue() instanceof Integer) {
				query.setInteger(param.getKey(), (Integer)param.getValue());
			} else if (param.getValue() instanceof Long) {
				query.setLong(param.getKey(), (Long)param.getValue());
			} else if (param.getValue() instanceof String) {
				query.setString(param.getKey(), (String)param.getValue());
			} else if (param.getValue() instanceof Boolean) {
				query.setBoolean(param.getKey(), (Boolean)param.getValue());
			} else if (param.getValue() instanceof Date) {
				query.setDate(param.getKey(), (Date)param.getValue());
			} else if (param.getValue() instanceof List) {
				List<?> list = (List<?>)param.getValue();
				if (!list.isEmpty() && list.get(0) instanceof Long)
					query.setParameterList(param.getKey(), list, new LongType());
				else if (!list.isEmpty() && list.get(0) instanceof String)
					query.setParameterList(param.getKey(), list, new StringType());
				else
					query.setParameterList(param.getKey(), list);
			} else {
				query.setString(param.getKey(), param.getValue().toString());
			}
		}
	}
	return query;
}
 
Example 30
Source Project: sakai   Source File: ProfileDaoImpl.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
public List<Message> getMessagesInThread(final String threadId) {
	
	final HibernateCallback<List<Message>> hcb = session -> {
           final Query q = session.getNamedQuery(QUERY_GET_MESSAGES_IN_THREAD);
           q.setParameter(THREAD, threadId, StringType.INSTANCE);
           return q.list();
       };
  	
  	return getHibernateTemplate().execute(hcb);
}