Java Code Examples for org.hibernate.transform.Transformers

The following are top voted examples for showing how to use org.hibernate.transform.Transformers. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: VoteUsrAttemptDAO.java   View source code 8 votes vote down vote up
@Override
   @SuppressWarnings("unchecked")
   public List<VoteStatsDTO> getStatisticsBySession(Long toolContentId) {

SQLQuery query = getSession().createSQLQuery(GET_STATISTICS);
query.addScalar("sessionUid", LongType.INSTANCE).addScalar("sessionName", StringType.INSTANCE)
	.addScalar("countUsersComplete", IntegerType.INSTANCE).setLong("contentId", toolContentId)
	.setResultTransformer(Transformers.aliasToBean(VoteStatsDTO.class));

return query.list();
   }
 
Example 2
Project: admin-shiro   File: DaoSupport.java   View source code 6 votes vote down vote up
@SuppressWarnings({"unchecked"})
public <T> Pagination<T> pageByHql(Class<T> clazz, CharSequence queryString, int pageIndex,
                                   int pageSize, Object... params) {
    Query query = getSession().createQuery(queryString.toString());

    if ((pageSize > 0) && (pageIndex > 0)) {
        query.setFirstResult((pageIndex - 1) * pageSize);
        query.setMaxResults(pageIndex * pageSize);
    }

    setParameter(query, params);
    query.setResultTransformer(Transformers.aliasToBean(clazz));

    List<T> items = query.list();
    Long rowsCount = (Long) getSingleColumnByHql(getCountStr(queryString.toString()), params);
    Pagination<T> pagination = new Pagination((long) pageIndex, (long) pageSize, rowsCount);
    pagination.setItems(items);
    return pagination;
}
 
Example 3
Project: spring-cloud-samples   File: BaseRepositoryImpl.java   View source code 6 votes vote down vote up
@Override
public <X> List<X> findByNative(String sql, List<?> params, Pageable pageable, Class<X> clazz) {
    Assert.hasText(sql, "native sql can not been null or blank");
    Query query = entityManager.createNativeQuery(sql);
    if (query != null) {
        query.unwrap(SQLQuery.class).setResultTransformer(Transformers.aliasToBean(clazz));
        query.setFirstResult(pageable.getOffset());
        query.setMaxResults(pageable.getPageSize());
        if (CollectionUtils.isNotEmpty(params)) {
            for (int i = 0; i < params.size(); i++) {
                query.setParameter(i + 1, params.get(i));
            }
        }
        return query.getResultList();
    }
    return Lists.newArrayList();
}
 
Example 4
Project: ImageClassify   File: ExportService.java   View source code 6 votes vote down vote up
@Override
public long exportHistoryLabelsNum() { 
	 long pages_num = 0;
	 Session session = HibernateUtils.getSession();//生成Session实例
	 Transaction tx=session.beginTransaction();//生成事务实例 
	 
	 try {
	     Query query = session.createSQLQuery("SELECT export_record.export_id,export_record.export_time,COUNT(*) AS amount FROM  "
		 		+ "export_record,export_tag WHERE export_record.export_id = export_tag.export_id GROUP BY export_record.export_id ORDER BY export_record.export_time DESC").setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP) ; 			  
	     pages_num  = query.list().size();	
	     tx.commit();//提交事务
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	}finally {
		HibernateUtils.closeSession();//关闭session实例
	}
	return pages_num;
}
 
Example 5
Project: ImageClassify   File: ContributeService.java   View source code 6 votes vote down vote up
@Override
public int getAmountContributeOfAllByUser() { 
	Session session = HibernateUtils.getSession();
	Transaction tx = session.beginTransaction();
	String sql = "SELECT id,upload_img_time,upload_img_review_status,username,tel_num FROM user_contribute_img WHERE upload_img_review_status=0 ORDER BY upload_img_time ASC";
	List<Contribute_Img > cImgs = new ArrayList<Contribute_Img>();
	try { 
		cImgs = session.createSQLQuery(sql).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).list();
		tx.commit(); 
	} catch (Exception e) {
		e.printStackTrace();
		tx.rollback();
	} finally {
		HibernateUtils.closeSession(); // 关闭Session实例
	} 
	return cImgs.size();
}
 
Example 6
Project: mblog   File: FollowDaoImpl.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public boolean checkCrossFollow(long userId, long targetUserId) {
	String hql = "from mto_follows where user_id = :userId and follow_id = :followId and " +
			"user_id in (select follow_id from mto_follows where user_id = :followId)";
	Query q = createSQLQuery(hql);
	q.setLong("userId", userId);
	q.setLong("followId", targetUserId);
	
	q.setResultTransformer(Transformers.aliasToBean(FollowPO.class));

	List<FollowPO> list = q.list();
	if (list != null && list.size() > 0) {
		return true;
	}
	return false;
}
 
Example 7
Project: singular-server   File: ActorDAO.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
public List<Actor> listAllowedUsers(Integer taskInstanceId) {
    StringBuilder sql = new StringBuilder();
    sql.append(" SELECT DISTINCT a.CO_ATOR AS \"cod\",");
    sql.append("   a.CO_USUARIO            AS \"codUsuario\",");
    sql.append("   UPPER(a.NO_ATOR)        AS \"nome\",");
    sql.append("   a.DS_EMAIL              AS \"email\"");
    sql.append(" FROM "+ Constants.SCHEMA +" .VW_ATOR a");
    sql.append(" ORDER BY UPPER(a.NO_ATOR)");
    SQLQuery query = getSession().createSQLQuery(sql.toString());
    query.addScalar("cod", StandardBasicTypes.INTEGER);
    query.addScalar("codUsuario", StandardBasicTypes.STRING);
    query.addScalar("nome", StandardBasicTypes.STRING);
    query.addScalar("email", StandardBasicTypes.STRING);
    query.setResultTransformer(Transformers.aliasToBean(Actor.class));
    return query.list();
}
 
Example 8
Project: coordinated-entry   File: SectionScoreDaoImplV3.java   View source code 6 votes vote down vote up
public List<ClientSurveyScore> calculateClientSurveyScore(Integer startIndex,Integer maxItems,String projectGroupCode) {
	DetachedCriteria criteria = DetachedCriteria.forClass(SectionScoreEntity.class);
	criteria.createAlias("surveyEntity", "surveyEntity");
	
	ProjectionList projectionList = Projections.projectionList();
	projectionList.add(Projections.sum("sectionScore"),"surveyScore");
	projectionList.add(Projections.property("surveyEntity.id"),"surveyId");
	projectionList.add(Projections.property("clientId"),"clientId");
	projectionList.add(Projections.property("surveyEntity.projectGroupCode"),"projectGroupCode");
	projectionList.add(Projections.property("surveyEntity.createdAt"),"surveyDate");
	projectionList.add(Projections.groupProperty("surveyEntity.id"));
	projectionList.add(Projections.groupProperty("clientId"));
	projectionList.add(Projections.groupProperty("surveyEntity.tagValue"),"surveyTagValue");
	criteria.setProjection(projectionList);
	criteria.add(Restrictions.eq("surveyEntity.projectGroupCode",projectGroupCode));
	criteria.setResultTransformer(Transformers.aliasToBean(ClientSurveyScore.class));
	return (List<ClientSurveyScore>) findByCriteria(criteria,startIndex,maxItems);
}
 
Example 9
Project: coordinated-entry   File: SectionScoreDaoImpl.java   View source code 6 votes vote down vote up
public List<ClientSurveyScore> calculateClientSurveyScore(Integer startIndex,Integer maxItems,String projectGroupCode) {
	DetachedCriteria criteria = DetachedCriteria.forClass(SectionScoreEntity.class);
	criteria.createAlias("surveyEntity", "surveyEntity");
	
	ProjectionList projectionList = Projections.projectionList();
	projectionList.add(Projections.sum("sectionScore"),"surveyScore");
	projectionList.add(Projections.property("surveyEntity.id"),"surveyId");
	projectionList.add(Projections.property("clientId"),"clientId");
	projectionList.add(Projections.property("surveyEntity.projectGroupCode"),"projectGroupCode");
	projectionList.add(Projections.property("surveyEntity.createdAt"),"surveyDate");
	projectionList.add(Projections.groupProperty("surveyEntity.id"));
	projectionList.add(Projections.groupProperty("clientId"));
	projectionList.add(Projections.groupProperty("surveyEntity.tagValue"),"surveyTagValue");
	criteria.setProjection(projectionList);
	criteria.add(Restrictions.eq("surveyEntity.projectGroupCode",projectGroupCode));
	criteria.setResultTransformer(Transformers.aliasToBean(ClientSurveyScore.class));
	return (List<ClientSurveyScore>) findByCriteria(criteria,startIndex,maxItems);
}
 
Example 10
Project: ArchBlock   File: ArchBlock.java   View source code 6 votes vote down vote up
/**
 * Get a list of all the UUIDs in a player's friends list.
 *
 * @param left The UUID of the player that owns the friends list we wish to get
 * @return A List of UUIDs of players in the friends list, which will be empty if no results were found
 */
public List getFriendships(UUID left) {
    Session s = this.plugin.getSession();

    Query q;

    q = s.createQuery(
            "SELECT f.friendUuid FROM Friendship f WHERE f.playerUuid=:uuid"
    );
    q.setString("uuid", left.toString());

    List r = q.list();

    if (r.size() < 1) {
        return r;
    }

    List result = s.createCriteria(com.archivesmc.archblock.storage.entities.Player.class)
            .add(Restrictions.in("uuid", r))
            .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP)
            .list();

    s.close();

    return result;
}
 
Example 11
Project: SpringCloud   File: BaseDaoImpl.java   View source code 6 votes vote down vote up
public <N extends Object> List<N> listBySql(String sql, Object[] args, Map<String, Object> alias, Class<?> clz,
        boolean hasEntiry) {
    sql = initSort(sql);
    SQLQuery sq = getSession().createSQLQuery(sql);
    setAliasParameter(sq, alias);
    setParameter(sq, args);
    if (hasEntiry) {

        sq.addEntity(clz);

    } else {

        sq.setResultTransformer(Transformers.aliasToBean(clz));
    }

    return sq.list();
}
 
Example 12
Project: high-performance-java-persistence   File: HibernateDTOProjectionTest.java   View source code 6 votes vote down vote up
@Test
public void testJpqlResultTransformer() {
    doInJPA( entityManager -> {
        List<PostDTO> postDTOs = entityManager.createQuery(
            "select " +
            "       p.id as id, " +
            "       p.title as title " +
            "from Post p " +
            "where p.createdOn > :fromTimestamp")
        .setParameter( "fromTimestamp", Timestamp.from(
            LocalDateTime.of( 2016, 1, 1, 0, 0, 0 ).toInstant( ZoneOffset.UTC ) ))
        .unwrap( org.hibernate.query.Query.class )
        .setResultTransformer( Transformers.aliasToBean( PostDTO.class ) )
        .getResultList();

        assertEquals( 1, postDTOs.size() );
    } );
}
 
Example 13
Project: high-performance-java-persistence   File: HibernateDTOProjectionTest.java   View source code 6 votes vote down vote up
@Test
public void testNativeQueryResultTransformer() {
    doInJPA( entityManager -> {
        List postDTOs = entityManager.createNativeQuery(
            "select " +
            "       p.id as \"id\", " +
            "       p.title as \"title\" " +
            "from Post p " +
            "where p.created_on > :fromTimestamp")
        .setParameter( "fromTimestamp", Timestamp.from(
            LocalDateTime.of( 2016, 1, 1, 0, 0, 0 ).toInstant( ZoneOffset.UTC ) ))
        .unwrap( org.hibernate.query.NativeQuery.class )
        .setResultTransformer( Transformers.aliasToBean( PostDTO.class ) )
        .getResultList();

        assertEquals( 1, postDTOs.size() );
    } );
}
 
Example 14
Project: sakai   File: ProfileDaoImpl.java   View source code 6 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
public List<UserProfile> getUserProfiles(final int start, final int count) {
	
	//get fields directly from the sakaiperson table and use Transformers.aliasToBean to transform into UserProfile pojo
	//the idea is we *dont* want a SakaiPerson object
	HibernateCallback<List<UserProfile>> hcb = session -> {
           Query q = session.getNamedQuery(QUERY_GET_SAKAI_PERSON);
           //see scalars in the hbm
           q.setFirstResult(start);
           q.setMaxResults(count);
           q.setResultTransformer(Transformers.aliasToBean(UserProfile.class));
           q.setCacheMode(CacheMode.GET);
           return q.list();
       };
  	
  	return getHibernateTemplate().execute(hcb);
}
 
Example 15
Project: gomall.la   File: BaseDaoImpl.java   View source code 6 votes vote down vote up
public PageSupport find(final SqlQuery sqlQuery) {
	return (PageSupport) getHibernateTemplate().execute(new HibernateCallback() {

		public Object doInHibernate(Session session) throws HibernateException, SQLException {
			SQLQuery query = session.createSQLQuery(sqlQuery.getQueryString());
			if (AppUtils.isNotBlank(sqlQuery.getEntityClass())) {
				for (String name : sqlQuery.getEntityClass().keySet()) {
					// query.addEntity(name,sqlQuery.getEntityClass().get(name));
					query.setResultTransformer(Transformers.aliasToBean(sqlQuery.getEntityClass().get(name)));
				}
			}
			SQLQuery allCountQuery = session.createSQLQuery(sqlQuery.getAllCountString());
			createSQLQuery(query, allCountQuery, sqlQuery.getParams(), sqlQuery.getParam(), sqlQuery.getTypes());

			// 得到总行数
			long allCounts = ((Number) allCountQuery.uniqueResult()).longValue();
			int curPageNO = PagerUtil.getCurPageNO(sqlQuery.getCurPage());
			int offset = PagerUtil.getOffset(allCounts, curPageNO, sqlQuery.getPageSize());
			query.setFirstResult(offset);
			query.setMaxResults(sqlQuery.getPageSize());
			return new PageSupport(query.list(), sqlQuery.getMyaction(), offset, curPageNO, allCounts, sqlQuery.getPageSize(),
					sqlQuery.getPageProvider());
		}
	});
}
 
Example 16
Project: EasyEE   File: CommonDAOSpringImpl.java   View source code 6 votes vote down vote up
/**
 * CommonDAO 内部方法, NativeQuery
 * 
 * @param entityManager
 *            entityManager
 * @param sql
 *            sql
 * @param values
 *            values
 * @return Query对象
 */
private Query createNativeQuery(EntityManager entityManager, String sql, Class resultClass, boolean mapResult,
		Map<String, Object> values) {
	Query query = null;
	if (resultClass != null) {
		query = entityManager.createNativeQuery(sql, resultClass);
	} else {
		query = entityManager.createNativeQuery(sql);
	}
	// 封装为Map结果
	if (mapResult) {
		query.unwrap(org.hibernate.Query.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
	}

	if (values != null && values.size() > 0) {
		for (Entry<String, Object> e : values.entrySet()) {
			query.setParameter(e.getKey(), e.getValue());
		}
	}
	return query;
}
 
Example 17
Project: EasyEE   File: CommonDAOSpringImpl.java   View source code 6 votes vote down vote up
/**
 * CommonDAO 内部方法, NativeQuery
 * 
 * @param entityManager
 *            entityManager
 * @param sql
 *            sql
 * @param values
 *            values
 * @return Query对象
 */
private Query createNativeQuery(EntityManager entityManager, String sql, Class resultClass, boolean mapResult,
		Map<String, Object> values) {
	Query query = null;
	if (resultClass != null) {
		query = entityManager.createNativeQuery(sql, resultClass);
	} else {
		query = entityManager.createNativeQuery(sql);
	}
	// 封装为Map结果
	if (mapResult) {
		query.unwrap(org.hibernate.Query.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
	}

	if (values != null && values.size() > 0) {
		for (Entry<String, Object> e : values.entrySet()) {
			query.setParameter(e.getKey(), e.getValue());
		}
	}
	return query;
}
 
Example 18
Project: EasyEE   File: CommonDAOSpringImpl.java   View source code 6 votes vote down vote up
/**
 * CommonDAO 内部方法, NativeQuery
 * 
 * @param entityManager
 *            entityManager
 * @param sql
 *            sql
 * @param values
 *            values
 * @return Query对象
 */
private Query createNativeQuery(EntityManager entityManager, String sql, Class resultClass, boolean mapResult,
		Map<String, Object> values) {
	Query query = null;
	if (resultClass != null) {
		query = entityManager.createNativeQuery(sql, resultClass);
	} else {
		query = entityManager.createNativeQuery(sql);
	}
	// 封装为Map结果
	if (mapResult) {
		query.unwrap(org.hibernate.Query.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
	}

	if (values != null && values.size() > 0) {
		for (Entry<String, Object> e : values.entrySet()) {
			query.setParameter(e.getKey(), e.getValue());
		}
	}
	return query;
}
 
Example 19
Project: imcms   File: LibraryService.java   View source code 6 votes vote down vote up
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public List<LibrariesDto> findLibraries(User user) {

    Session session = getCurrentSession();

    if (user.isSuperAdmin()) {
        return session.createQuery(
                "SELECT lib.id AS id, lib.libraryNm AS libraryNm, lib.filepath AS filepath, lib.folderNm AS folderNm" +
                        " FROM Libraries lib ORDER BY lib.libraryNm")
                .setResultTransformer(Transformers.aliasToBean(LibrariesDto.class))
                .list();
    }

    List<Integer> roleIds = UserService.getRoleIds(user);
    if (roleIds.isEmpty()) {
        return Collections.EMPTY_LIST;
    }

    return session.createQuery(
            "SELECT DISTINCT lib.id AS id, lib.libraryNm AS libraryNm, lib.filepath AS filepath, lib.folderNm AS folderNm" +
                    " FROM LibraryRoles lr INNER JOIN lr.library lib " +
                    "WHERE lr.roleId IN (:roleIds) ORDER BY lib.libraryNm ")
            .setParameterList("roleIds", roleIds)
            .setResultTransformer(Transformers.aliasToBean(LibrariesDto.class))
            .list();
}
 
Example 20
Project: imcms   File: ImageService.java   View source code 6 votes vote down vote up
@Transactional(readOnly = true)
public List<Categories> findAvailableImageCategories(long imageId, User user) {

    Session session = getCurrentSession();

    if (user.isSuperAdmin()) {
        return session.getNamedQuery("availableImageCategoriesAdmin")
                .setLong("imageId", imageId)
                .setResultTransformer(Transformers.aliasToBean(Categories.class))
                .list();
    }

    Set<Integer> roleIds = facade.getUserService().getRoleIdsWithPermission(user, null, RoleDomainObject.CHANGE_IMAGES_IN_ARCHIVE_PERMISSION);
    if (roleIds.isEmpty()) {
        return Collections.EMPTY_LIST;
    }

    return session.getNamedQuery("availableImageCategories")
            .setLong("imageId", imageId)
            .setParameterList("roleIds", roleIds)
            .setResultTransformer(Transformers.aliasToBean(Categories.class))
            .list();
}
 
Example 21
Project: shogun2   File: GenericHibernateDao.java   View source code 6 votes vote down vote up
/**
 * Gets the results, that match a variable number of passed criterions, but return a
 * stripped version of the entities, where only the fieldNames in <code>restrictFieldNames</code>
 * have their actual values set.
 *
 * You can call this with <code>restrictFieldNames</code> = <code>null</code> to get the full
 * entities back.
 *
 * You can call this method without criterion arguments to find all entities (stripped down to
 * the <code>restrictFieldNames</code>).
 *
 * If this is called as <code>findByCriteriaRestricted(null)</code> the return value equals the
 * return value of <code>findByCriteria()</code>.
 *
 * @param restrictFieldNames
 * @param criterion
 * @return
 * @throws HibernateException
 */
@SuppressWarnings("unchecked")
public List<E> findByCriteriaRestricted(List<String> restrictFieldNames, Criterion... criterion) throws HibernateException {
	LOG.trace("Finding instances of " + entityClass.getSimpleName()
			+ " based on " + criterion.length + " criteria");

	Criteria criteria = createDistinctRootEntityCriteria(criterion);

	if (restrictFieldNames != null){
		ProjectionList projectionList = Projections.projectionList();
		for (String restrictFieldName : restrictFieldNames) {
			PropertyProjection pp = Projections.property(restrictFieldName);
			projectionList.add(pp, restrictFieldName);
		}
		criteria.setProjection(projectionList);
		criteria.setResultTransformer(
			Transformers.aliasToBean(entityClass)
		);
	}

	return criteria.list();
}
 
Example 22
Project: Harvest-JP   File: HeadquartersServiceImpl.java   View source code 6 votes vote down vote up
/** {@inheritDoc} */
  @Override
  public HeadquartersMessageBean findLatestNews() {
  	final Session session = HibernateSessionManager.getSession();
   Transaction tx = null;
   
   HeadquartersMessageBean headquartersMessage = null;
   try {
	tx = session.beginTransaction();
	Query namedQuery = repository.getNamedQuery(session, SqlConstants.SQL_FIND_HEADQUATER_MESSAGE)
       		.setResultTransformer(Transformers.aliasToBean(HeadquartersMessageBean.class));
       List<HeadquartersMessageBean> latestNews = namedQuery.list();
       if (CollectionUtils.isNotEmpty(latestNews)) {
       	headquartersMessage = latestNews.get(0);
       }
       tx.commit();
} catch (HibernateException ex) {
	if (tx != null) {
		tx.rollback();
	}
	throw new ServiceException(ex);
} finally {
	HibernateSessionManager.closeSession(session);
}
   return headquartersMessage;
  }
 
Example 23
Project: Harvest-JP   File: HeadquartersServiceImpl.java   View source code 6 votes vote down vote up
@Override
  public List<HeadquartersMessageBean> findByOffset(int position, int offset) throws ServiceException {
  	final Session session = HibernateSessionManager.getSession();
   Transaction tx = null;
   
   List<HeadquartersMessageBean> latestNews = new ArrayList<>();
   try {
   	tx = session.beginTransaction();
       Query namedQuery = repository.getNamedQuery(session, SqlConstants.SQL_FIND_HEADQUATER_MESSAGE)
       		.setFirstResult(position)
       		.setMaxResults(offset)
       		.setResultTransformer(Transformers.aliasToBean(HeadquartersMessageBean.class));
       latestNews = namedQuery.list();
       tx.commit();
} catch (HibernateException ex) {
	if (tx != null) {
		tx.rollback();
	}
	throw new ServiceException(ex);
} finally {
	HibernateSessionManager.closeSession(session);
}
      return latestNews;
  }
 
Example 24
Project: Harvest-JP   File: MenuGroupServiceImpl.java   View source code 6 votes vote down vote up
/** {@inheritDoc} */
@Override
@SuppressWarnings("unchecked")
public List<ProcessGroupBean> findAllGroups() throws ServiceException {
	final Session session = HibernateSessionManager.getSession();
	Transaction tx = null;
	
	List<ProcessGroupBean> processGroupBeans = new ArrayList<>();
	try {
		tx = session.beginTransaction();
		Query query = repository.getQuery(session, "SELECT a.proGName FROM AT108 a GROUP BY a.proGName ORDER BY a.proGName DESC")
				.setResultTransformer(Transformers.aliasToBean(ProcessGroupBean.class));
		processGroupBeans = query.list();
		tx.commit();
	} catch (HibernateException ex) {
		if (tx != null) {
			tx.rollback();
		}
		throw new ServiceException("An error occurred when getting all groups", ex);
	} finally {
		HibernateSessionManager.closeSession(session);
	}
	return processGroupBeans;
}
 
Example 25
Project: zswxsqxt   File: GenericSQLDao.java   View source code 6 votes vote down vote up
private List findFastBySql(String sql, Class resultType,
		List<ResultMapping> resultMappingList, Object... args) {
	SQLQuery dataQuery = getSession().createSQLQuery(sql);
	if(!resultType.getName().equals(HashMap.class.getName()))
	{
		dataQuery.setResultTransformer(Transformers.aliasToBean(resultType));
		for (ResultMapping mapping : resultMappingList) {
			dataQuery.addScalar(mapping.getProperty(), mapping .getHibernateType());
		}
	}else
	{
		dataQuery.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
	}
	for (int i = 0; i < args.length; i++) {
		dataQuery.setParameter(i, args[i]);
	}
	return dataQuery.list();
}
 
Example 26
Project: sakai   File: ProfileDaoImpl.java   View source code 6 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
public List<UserProfile> getUserProfiles(final int start, final int count) {
	
	//get fields directly from the sakaiperson table and use Transformers.aliasToBean to transform into UserProfile pojo
	//the idea is we *dont* want a SakaiPerson object
	HibernateCallback<List<UserProfile>> hcb = session -> {
           Query q = session.getNamedQuery(QUERY_GET_SAKAI_PERSON);
           //see scalars in the hbm
           q.setFirstResult(start);
           q.setMaxResults(count);
           q.setResultTransformer(Transformers.aliasToBean(UserProfile.class));
           q.setCacheMode(CacheMode.GET);
           return q.list();
       };
  	
  	return getHibernateTemplate().execute(hcb);
}
 
Example 27
Project: debop4j   File: HibernateRepository.java   View source code 6 votes vote down vote up
/**
 * Build projection criteria.
 *
 * @param projectClass   the project class
 * @param criteria       the criteria
 * @param projection     the projection
 * @param distinctResult the distinct result
 * @return the criteria
 */
protected <TProject> Criteria buildProjectionCriteria(Class<TProject> projectClass,
                                                      Criteria criteria,
                                                      Projection projection,
                                                      boolean distinctResult) {
    if (isTraceEnabled)
        log.trace("Criteria에 Projection을 적용합니다. projectClass=[{}], projection=[{}], distinctResult=[{}]",
                  projectClass, projection, distinctResult);

    if (distinctResult) {
        criteria.setProjection(Projections.distinct(projection));
    } else {
        criteria.setProjection(projection);
    }

    criteria.setResultTransformer(Transformers.aliasToBean(projectClass));
    return criteria;
}
 
Example 28
Project: debop4j   File: HibernateDao.java   View source code 6 votes vote down vote up
/**
 * Build projection criteria.
 *
 * @param projectClass   the project class
 * @param criteria       the criteria
 * @param projection     the projection
 * @param distinctResult the distinct result
 * @return the criteria
 */
protected <TProject> Criteria buildProjectionCriteria(Class<TProject> projectClass,
                                                      Criteria criteria,
                                                      Projection projection,
                                                      boolean distinctResult) {
    if (isTraceEnabled)
        log.trace("Criteria에 Projection을 적용합니다. projectClass=[{}], projection=[{}], distinctResult=[{}]",
                  projectClass, projection, distinctResult);

    if (distinctResult) {
        criteria.setProjection(Projections.distinct(projection));
    } else {
        criteria.setProjection(projection);
    }

    criteria.setResultTransformer(Transformers.aliasToBean(projectClass));
    return criteria;
}
 
Example 29
Project: chipster   File: StatDataSource.java   View source code 6 votes vote down vote up
@SuppressWarnings("rawtypes")
private Map getJobDateRange(Session session, boolean ignoreTestAccounts) {
	//Get min and max values of dates
	Criteria rangeCriteria = session.createCriteria(JobLogEntry.class);
	testAccountFilter.addCriteriaForTestAccounts(session, ignoreTestAccounts, rangeCriteria);
	ProjectionList projections = Projections.projectionList();
	projections.add(Projections.min(JobLogContainer.START_TIME), "min");
	projections.add(Projections.max(JobLogContainer.START_TIME), "max");
	rangeCriteria.setProjection(projections);
	rangeCriteria.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

	@SuppressWarnings("unchecked")
	List<Map> rangeList = rangeCriteria.list();

	return rangeList.get(0);
}
 
Example 30
Project: replyit-master-3.2-final   File: UsageDAS.java   View source code 6 votes vote down vote up
public Usage findUsageByItem(Integer excludedOrderId, Integer itemId, Integer userId, Date startDate, Date endDate) {
    String sql = excludedOrderId != null
                 ? USAGE_BY_ITEM_ID_SQL + EXCLUDE_ORDER_ID_CLAUSE
                 : USAGE_BY_ITEM_ID_SQL;

    Query query = getSession().createSQLQuery(sql)
            .addScalar("amount")
            .addScalar("quantity")
            .setResultTransformer(Transformers.aliasToBean(Usage.class));

    query.setParameter("user_id", userId);
    query.setParameter("item_id", itemId);
    query.setParameter("start_date", startDate);
    query.setParameter("end_date", endDate);

    if (excludedOrderId != null)
        query.setParameter("excluded_order_id", excludedOrderId);

    Usage usage = (Usage) query.uniqueResult();
    usage.setUserId(userId);
    usage.setItemId(itemId);
    usage.setStartDate(startDate);
    usage.setEndDate(endDate);

    return usage;
}
 
Example 31
Project: myanmarlottery   File: ResultRepositoryImpl.java   View source code 5 votes vote down vote up
@Override
public Result findLatestResultSummary(int type) {
    log.info("findByNumberOfTimes..");
    return (Result) getSession()
            .getNamedQuery("result.findLatestResultSummary")
            .setInteger("type", type)
            .setResultTransformer(Transformers.aliasToBean(Result.class)).uniqueResult();
}
 
Example 32
Project: agile-wroking-backend   File: ScheduleRepositoryImpl.java   View source code 5 votes vote down vote up
/**
 * 自定义 native query 查询 {@link ScheduleVO} ,略繁琐但是好像没有更好的办法.
 */
@Transactional
@Override
public List<ScheduleVO> findByOpenIdAndDate(String openId, Date date) {
	String sql = "select  t.schedule_id as scheduleId  ,t.date,t.meeting_room_id  as meetingRoomId,t.title,t.open_id as openId,m.room_no as roomNo,t.start_time as startTime,t.end_time as endTime, t.repeat_mode as repeatMode   from (select  p.schedule_id,p.date,s.meeting_room_id,s.title,p.open_id,s.start_time,s.end_time,s.repeat_mode from participant p left join  schedule  s on    p.schedule_id = s.id  ) as t left join meeting_room m on t.meeting_room_id  = m.id  where (t.open_id=? and t.date=?) or (t.open_id=? and repeat_mode='W')";
	Session session = entityManager.unwrap(org.hibernate.Session.class);
	SQLQuery query = session.createSQLQuery(sql);
	@SuppressWarnings("unchecked")
	List<ScheduleVO> scheduleVOs = query.setResultTransformer(Transformers.aliasToBean(ScheduleVO.class))
			.setParameter(0, openId).setParameter(1, date).setParameter(2, openId).list();
	return scheduleVOs.stream().filter(s -> s.isNeedInclude(date)).map(s -> {
		s.setDate(date);
		return s;
	}).sorted().collect(Collectors.toList());
}
 
Example 33
Project: agile-wroking-backend   File: ScheduleRepositoryImpl.java   View source code 5 votes vote down vote up
@Transactional
@Override
public List<ScheduleVO> findByDate(Date date) {
	String sql = "select  t.schedule_id as scheduleId  ,t.date,t.meeting_room_id  as meetingRoomId,t.title,t.open_id as openId,m.room_no as roomNo,t.start_time as startTime,t.end_time as endTime, t.repeat_mode as repeatMode   from (select  p.schedule_id,p.date,s.meeting_room_id,s.title, s.creator_open_id open_id,s.start_time,s.end_time,s.repeat_mode from participant p left join  schedule  s on    p.schedule_id = s.id  ) as t left join meeting_room m on t.meeting_room_id  = m.id  where (t.date=?) or (repeat_mode='W')";
	Session session = entityManager.unwrap(org.hibernate.Session.class);
	SQLQuery query = session.createSQLQuery(sql);
	@SuppressWarnings("unchecked")
	List<ScheduleVO> scheduleVOs = query.setResultTransformer(Transformers.aliasToBean(ScheduleVO.class))
			.setParameter(0, date).list();
	return scheduleVOs.stream().filter(s -> s.isNeedInclude(date)).map(s -> {
		s.setDate(date);
		return s;
	}).sorted().collect(Collectors.toList());

}
 
Example 34
Project: sucok-framework   File: BaseDao.java   View source code 5 votes vote down vote up
/**
 * 执行原生SQL查询
 * @param sql
 * @param params sql参数
 * @return 结果集并影射成Map
 */
public List<Map<String,Object>> queryByNativeSQL(String sql,Map<String,Object> params){
	Query query=em.createNativeQuery(sql);
	if(params!=null&&params.size()>0){
		for(String param:params.keySet() ){
			query.setParameter(param,params.get(param));
		}
	}
	query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
	return query.getResultList();
}
 
Example 35
Project: sucok-framework   File: BaseDao.java   View source code 5 votes vote down vote up
/**
 * 执行原生SQL查询
 * @param sql
 * @param params sql参数
 * @return 结果集并影射成Map
 */
public List<Map<String,Object>> queryByNativeSQL(String sql,Object... params){
	Query query=em.createNativeQuery(sql);
	if(params!=null&&params.length>0){
		for(int i=0;i< params.length;i++){
			query.setParameter(i,params[i]);
		}
	}
	query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
	return query.getResultList();
}
 
Example 36
Project: lams   File: PeerreviewDAOHibernate.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
   @Override
   public List<PeerreviewStatisticsDTO> getStatistics(Long toolContentId) {
return getSession().createSQLQuery(GET_STATS)
	.setLong("toolContentId", toolContentId)
	.setResultTransformer( Transformers.aliasToBean( PeerreviewStatisticsDTO.class ) )
	.list();

   }
 
Example 37
Project: lams   File: DacoSessionDAOHibernate.java   View source code 5 votes vote down vote up
@Override
   public List<MonitoringSummarySessionDTO> statistics(Long toolContentUid) {
SQLQuery query = getSession().createSQLQuery(DacoSessionDAOHibernate.CALC_SESSION_STATS);
query.addScalar("sessionId", LongType.INSTANCE).addScalar("sessionName", StringType.INSTANCE)
	.addScalar("numberLearners", IntegerType.INSTANCE).addScalar("totalRecordCount", IntegerType.INSTANCE)
	.setLong("contentUid", toolContentUid)
	.setResultTransformer(Transformers.aliasToBean(MonitoringSessionStatsDTO.class));
return query.list();

   }
 
Example 38
Project: lams   File: ConstructorNode.java   View source code 5 votes vote down vote up
@Override
public ResultTransformer getResultTransformer() {
	if ( constructor != null ) {
		return new AliasToBeanConstructorResultTransformer( constructor );
	}
	else if ( isMap ) {
		return Transformers.ALIAS_TO_ENTITY_MAP;
	}
	else if ( isList ) {
		return Transformers.TO_LIST;
	}
	throw new QueryException( "Unable to determine proper dynamic-instantiation tranformer to use." );
}
 
Example 39
Project: lams   File: HolderInstantiator.java   View source code 5 votes vote down vote up
public static ResultTransformer createSelectNewTransformer(Constructor constructor, boolean returnMaps, boolean returnLists) {
	if ( constructor != null ) {
		return new AliasToBeanConstructorResultTransformer(constructor);
	}
	else if ( returnMaps ) {
		return Transformers.ALIAS_TO_ENTITY_MAP;			
	}
	else if ( returnLists ) {
		return Transformers.TO_LIST;
	}		
	else {
		return null;
	}
}
 
Example 40
Project: lams   File: NotebookUserDAO.java   View source code 5 votes vote down vote up
@Override
   @SuppressWarnings("unchecked")
   public List<StatisticDTO> getStatisticsBySession(final Long contentId) {
SQLQuery query = getSession().createSQLQuery(GET_STATISTICS);
query.addScalar("sessionId", LongType.INSTANCE).addScalar("sessionName", StringType.INSTANCE)
	.addScalar("numLearners", IntegerType.INSTANCE).addScalar("numLearnersFinished", IntegerType.INSTANCE)
	.setLong("contentId", contentId).setResultTransformer(Transformers.aliasToBean(StatisticDTO.class));
return query.list();
   }