org.hibernate.transform.Transformers Java Examples

The following examples show how to use org.hibernate.transform.Transformers. 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
Source Project: jbang   Author: jbangdev   File: hibernate.java    License: MIT License 6 votes vote down vote up
void run() {
    var db = setup().openStatelessSession();

    var sqlString = "SELECT first_name as firstName, last_name as lastName, count(*) films\n" +
            "FROM actor AS a\n" +
            "JOIN film_actor AS fa USING (actor_id)\n" +
            "GROUP BY a.actor_id, first_name, last_name\n" +
            "ORDER BY films DESC\n" +
            "LIMIT 10";


    db.createNativeQuery(sqlString)
    .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP).stream().forEach(o -> out.println(o));

    //need other public classes which jbang can't compile/include at the moment.
    //db.createNativeQuery(sqlString).addScalar("firstName").addScalar("lastName").addScalar("films")
    //        .setResultTransformer(Transformers.aliasToBean(DTO.class)).stream().forEach(o -> out.println(o));

}
 
Example #2
Source Project: oim-fx   Author: oimchat   File: BaseAbstractDAO.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> T queryUniqueResult(String queryString, QueryWrapper queryWrapper, Class<T> resultClass, List<ResultType> returnTypeList) {
	Session session = sessionBox.getCurrentSession();
	Query query = createSQLQuery(session, queryString);
	setParameter(query, queryWrapper);
	setScalar(query, returnTypeList);

	if (resultClass != null && !this.isPrimitive(resultClass) && !this.isString(resultClass)) {
		if (null == returnTypeList || returnTypeList.isEmpty()) {
			query.setResultTransformer(new ResultToBean(resultClass));
		} else {
			query.setResultTransformer(Transformers.aliasToBean(resultClass));
		}
	}
	if (null == resultClass) {
		query.setResultTransformer(new ResultToBean(resultClass));
	}
	Object value = query.uniqueResult();
	if (value instanceof BigInteger) {
		if (Long.class == resultClass) {
			value = ((BigInteger) value).longValue();
		}
	}
	return (T) value;
}
 
Example #3
Source Project: ueboot   Author: ueboot   File: DefaultJpaRepository.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public <S> Page<S> find(String queryString, String queryCount, NamedParams params, Pageable pageable, Class<S> transformer) {
    Assert.hasText(queryString, "Query must has text!");
    Assert.hasText(queryCount, "Query count must has text!");
    Assert.notNull(params, "QueryParams must not be null!");
    Assert.notNull(pageable, "PageRequest must not be null!");
    Assert.notNull(transformer, "TransformerClass must not be null!");

    Query query = em.createQuery(queryString);

    setQueryParams(query, params);
    query.setMaxResults(pageable.getPageSize());
    query.setFirstResult((int) pageable.getOffset());

    List<S> resultList = query.unwrap(QueryImpl.class).setResultTransformer(Transformers.aliasToBean(transformer)).list();

    Query countQuery = em.createQuery(queryCount);
    setQueryParams(countQuery, params);
    Long total = (Long) countQuery.getSingleResult();

    Page<S> page = new PageImpl(resultList, pageable, total);

    return page;
}
 
Example #4
Source Project: ueboot   Author: ueboot   File: DefaultJpaRepository.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public <S> List<S> findBySql(StringQuery stringQuery, Class<S> transformer) {
    Assert.notNull(stringQuery, "StringQuery must not be null!");

    String sql = stringQuery.getQuery();
    NamedParams params = stringQuery.getParams();

    Assert.notNull(params, "NamedParams must not be null!");

    Query query = em.createNativeQuery(sql);
    setQueryParams(query, params);

    NativeQuery sqlQuery = query.unwrap(NativeQuery.class);
    stringQuery.getScalars().forEach((s, type) -> {
        sqlQuery.addScalar(s, type);
    });

    return sqlQuery.setResultTransformer(Transformers.aliasToBean(transformer)).list();
}
 
Example #5
Source Project: Knowage-Server   Author: KnowageLabs   File: ProductTypeDAOHibImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List loadOrganizzationEngines(final String tenant) {

	List orgEngs = list(new ICriterion() {
		@Override
		public Criteria evaluate(Session session) {
			return session
					.createCriteria(SbiEngines.class)
					.createAlias("sbiProductTypeEngine", "_sbiProductTypeEngine")
					.createAlias("_sbiProductTypeEngine.sbiProductType", "_sbiProductType")
					.createAlias("_sbiProductType.sbiOrganizationProductType", "_sbiOrganizationProductType")
					.createAlias("_sbiOrganizationProductType.sbiOrganizations", "_sbiOrganizations")
					.add(Restrictions.eq("_sbiOrganizations.name", tenant))
					.setProjection(
							Projections.projectionList().add(org.hibernate.criterion.Property.forName("label").as("engineLabel"))
									.add(org.hibernate.criterion.Property.forName("_sbiProductType.label").as("productTypeLabel")))
					.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		}
	});
	return orgEngs;
}
 
Example #6
Source Project: Knowage-Server   Author: KnowageLabs   File: SearchGlossaryByName.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public Criteria evaluate(Session session) {
	Criteria criteria = session.createCriteria(SbiGlGlossary.class);
	criteria.setProjection(
			Projections.projectionList().add(Projections.property("glossaryId"), "glossaryId").add(Projections.property("glossaryNm"), "glossaryNm"))
			.setResultTransformer(Transformers.aliasToBean(SbiGlGlossary.class));
	if (glossary != null && !glossary.isEmpty()) {
		criteria.add(Restrictions.like("glossaryNm", glossary, MatchMode.ANYWHERE).ignoreCase());
	}

	if (page != null && itemsPerPage != null) {
		criteria.setFirstResult((page - 1) * itemsPerPage);
		criteria.setMaxResults(itemsPerPage);
	}

	return criteria;
}
 
Example #7
Source Project: Knowage-Server   Author: KnowageLabs   File: KpiDAOImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<String> listPlaceholderByMeasures(final List<String> measures) {
    List<SbiKpiPlaceholder> lst = list(new ICriterion<SbiKpiPlaceholder>() {
        @Override
        public Criteria evaluate(Session session) {
            DetachedCriteria detachedCriteria = DetachedCriteria.forClass(SbiKpiRuleOutput.class).createAlias("sbiKpiRule", "sbiKpiRule")
                    .createAlias("sbiKpiAlias", "sbiKpiAlias").setProjection(Property.forName("sbiKpiRule.sbiKpiRuleId.id"))
                    .add(Restrictions.eq("sbiKpiRule.active", 'T')).add(Restrictions.in("sbiKpiAlias.name", measures));

            Criteria c = session.createCriteria(SbiKpiRule.class).createAlias("sbiKpiPlaceholders", "sbiKpiPlaceholders")
                    .add(Property.forName("sbiKpiRuleId.id").in(detachedCriteria)).add(Restrictions.eq("active", 'T'))
                    .setProjection(Projections.distinct(Projections.property("sbiKpiPlaceholders.name").as("name")))
                    .setResultTransformer(Transformers.aliasToBean(SbiKpiPlaceholder.class));
            return c;
        }
    });
    List<String> placeholdername = new ArrayList<>();
    for (SbiKpiPlaceholder sbiKpiPlaceholder : lst) {
        placeholdername.add(sbiKpiPlaceholder.getName());
    }
    return placeholdername;
}
 
Example #8
Source Project: Knowage-Server   Author: KnowageLabs   File: KpiDAOImpl.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public List<Threshold> listThreshold() {
    List<SbiKpiThreshold> sbiLst = list(new ICriterion<SbiKpiThreshold>() {
        @Override
        public Criteria evaluate(Session session) {
            return session
                    .createCriteria(SbiKpiThreshold.class)
                    .setProjection(
                            Projections.projectionList().add(Projections.property("id"), "id").add(Projections.property("name"), "name")
                                    .add(Projections.property("description"), "description"))
                    .setResultTransformer(Transformers.aliasToBean(SbiKpiThreshold.class));
        }
    });
    List<Threshold> thresholds = new ArrayList<>();
    for (SbiKpiThreshold sbiThreshold : sbiLst) {
        thresholds.add(from(sbiThreshold, false));
    }
    return thresholds;
}
 
Example #9
Source Project: wangmarket   Author: xnx3   File: SqlDAO.java    License: Apache License 2.0 6 votes vote down vote up
/**
	 * 传入查询的原生SQL语句
	 * @param sqlQuery 原生SQL语句
	 * @return List<Map<String,String>>
	 */
	public List<Map<String,Object>> findMapBySqlQuery(String sqlQuery){
//		try {
//			Query queryObject = getCurrentSession().createSQLQuery(sqlQuery).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
//			return queryObject.list();
//		} catch (RuntimeException re) {
//			throw re;
//		}
		
		javax.persistence.Query query = entityManager.createNativeQuery(sqlQuery);
//		query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		query.unwrap(Query.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
		List<Map<String,Object>> list= query.getResultList();
        entityManager.close();
        return list;
	}
 
Example #10
Source Project: wetech-cms   Author: cjbi   File: BaseDao.java    License: MIT License 6 votes vote down vote up
public <N extends Object>Pager<N> findBySql(String sql, Object[] args,
		Map<String, Object> alias, Class<?> clz, boolean hasEntity) {
	sql = initSort(sql);
	String cq = getCountHql(sql,false);
	SQLQuery sq = getSession().createSQLQuery(sql);
	SQLQuery cquery = getSession().createSQLQuery(cq);
	setAliasParameter(sq, alias);
	setAliasParameter(cquery, alias);
	setParameter(sq, args);
	setParameter(cquery, args);
	Pager<N> pages = new Pager<N>();
	setPagers(sq, pages);
	if(hasEntity) {
		sq.addEntity(clz);
	} else {
		sq.setResultTransformer(Transformers.aliasToBean(clz));
	}
	List<N> datas = sq.list();
	pages.setDatas(datas);
	long total = ((BigInteger)cquery.uniqueResult()).longValue();
	pages.setTotal(total);
	return pages;
}
 
Example #11
Source Project: SpringCloud   Author: SoftwareKing   File: BaseDaoImpl.java    License: Apache License 2.0 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
Source Project: high-performance-java-persistence   Author: vladmihalcea   File: GroupConcatFunctionDefaultTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@Ignore
public void testGroupConcatJPQLQuery() {
    doInJPA(entityManager -> {
        List<PostSummaryDTO> postSummaries = entityManager.createQuery(
            "select " +
            "   p.id as id, " +
            "   p.title as title, " +
            "   group_concat(t.name) as tags " +
            "from Post p " +
            "left join p.tags t " +
            "group by p.id, p.title")
        .unwrap(Query.class)
        .setResultTransformer(Transformers.aliasToBean(PostSummaryDTO.class))
        .getResultList();

        assertEquals(1, postSummaries.size());
        LOGGER.info("Post tags: {}", postSummaries.get(0).getTags());
    });
}
 
Example #13
@Test
@Ignore
public void testGroupConcatJPQLQuery() {
    doInJPA(entityManager -> {
        List<PostSummaryDTO> postSummaries = entityManager.createQuery(
            "select " +
            "   p.id as id, " +
            "   p.title as title, " +
            "   group_concat(t.name) as tags " +
            "from Post p " +
            "left join p.tags t " +
            "group by p.id, p.title")
        .unwrap(Query.class)
        .setResultTransformer(Transformers.aliasToBean(PostSummaryDTO.class))
        .getResultList();

        assertEquals(1, postSummaries.size());
        LOGGER.info("Post tags: {}", postSummaries.get(0).getTags());
    });
}
 
Example #14
@Test
public void testGroupConcatJPQLQuery() {
    doInJPA(entityManager -> {
        List<PostSummaryDTO> postSummaries = entityManager.createQuery(
            "select " +
            "   p.id as id, " +
            "   p.title as title, " +
            "   group_concat(t.name) as tags " +
            "from Post p " +
            "left join p.tags t " +
            "group by p.id, p.title")
        .unwrap(Query.class)
        .setResultTransformer(Transformers.aliasToBean(PostSummaryDTO.class))
        .getResultList();

        assertEquals(1, postSummaries.size());
        LOGGER.info("Post tags: {}", postSummaries.get(0).getTags());
    });
}
 
Example #15
@Test
public void testGroupConcatJPQLQuery() {
    doInJPA(entityManager -> {
        List<PostSummaryDTO> postSummaries = entityManager.createQuery(
            "select " +
            "   p.id as id, " +
            "   p.title as title, " +
            "   group_concat(t.name) as tags " +
            "from Post p " +
            "left join p.tags t " +
            "group by p.id, p.title")
        .unwrap(Query.class)
        .setResultTransformer(Transformers.aliasToBean(PostSummaryDTO.class))
        .getResultList();

        assertEquals(1, postSummaries.size());
        LOGGER.info("Post tags: {}", postSummaries.get(0).getTags());
    });
}
 
Example #16
Source Project: chipster   Author: chipster   File: StatDataSource.java    License: MIT License 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 #17
Source Project: sakai   Author: sakaiproject   File: ProfileDaoImpl.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
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
	final HibernateCallback<List<UserProfile>> hcb = session -> {
           final 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 #18
Source Project: EasyEE   Author: ushelp   File: CommonDAOSpringImpl.java    License: MIT License 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
Source Project: EasyEE   Author: ushelp   File: CommonDAOSpringImpl.java    License: MIT License 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 #20
Source Project: EasyEE   Author: ushelp   File: CommonDAOSpringImpl.java    License: MIT License 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 #21
Source Project: sakai   Author: sakaiproject   File: ProfileDaoImpl.java    License: Educational Community License v2.0 6 votes vote down vote up
/**
	 * {@inheritDoc}
	 */
@Override
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
	final HibernateCallback<List<UserProfile>> hcb = session -> {
           final 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 #22
Source Project: ZTuoExchange_framework   Author: sengeiou   File: MemberPromotionService.java    License: MIT License 5 votes vote down vote up
public Page<RegisterPromotionVO> getPromotionDetails(long memberId, PageModel pageModel){

        StringBuilder headSql = new StringBuilder("select a.id id ,a.username presentee,a.email presenteeEmail, ")
                .append("a.mobile_phone presenteePhone,a.real_name presenteeRealName,a.registration_time promotionTime, ")
                .append("b.level promotionLevel ") ;

        StringBuilder endSql = new StringBuilder(" from member a join member_promotion b on a.inviter_id = b.inviter_id and a.inviter_id = "+memberId);

        StringBuilder countHead = new StringBuilder("select count(*) ") ;
        Page<RegisterPromotionVO> page = createNativePageQuery(countHead.append(endSql),headSql.append(endSql),pageModel,Transformers.aliasToBean(RegisterPromotionVO.class)) ;
        RewardPromotionSetting setting = rewardPromotionSettingService.findByType(PromotionRewardType.REGISTER) ;

        BigDecimal one = JSONObject.parseObject(setting.getInfo()).getBigDecimal("one");
        BigDecimal two = JSONObject.parseObject(setting.getInfo()).getBigDecimal("two");

        for(RegisterPromotionVO vo:page.getContent()){
            vo.setUnit(setting.getCoin().getUnit());
            if(vo.getPromotionLevel()== PromotionLevel.ONE.getOrdinal()){
                vo.setReward(one);
            }else if(vo.getPromotionLevel()== PromotionLevel.TWO.getOrdinal()){
                vo.setReward(two);
            }else{
                vo.setReward(BigDecimal.ZERO);
            }
        }
        return page ;
    }
 
Example #23
Source Project: ZTuoExchange_framework   Author: sengeiou   File: OrderService.java    License: MIT License 5 votes vote down vote up
public Map getOrderBySn(Long memberId, String orderSn) {
    String sql = "select o.*,m.real_name from otc_order o  join member m on o.customer_id=m.id and o.member_id=:memberId and o.order_sn =:orderSn ";
    Query query = em.createNativeQuery(sql);
    //设置结果转成Map类型
    query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    Object object = query.setParameter("memberId", memberId).setParameter("orderSn", orderSn).getSingleResult();
    Map map = (HashMap) object;
    return map;
}
 
Example #24
Source Project: ZTuoExchange_framework   Author: sengeiou   File: AdminService.java    License: MIT License 5 votes vote down vote up
public Map findAdminDetail(Long id) {
    String sql = "select a.id,a.role_id roleId,a.department_id departmentId,a.real_name realName,a.avatar,a.email,a.enable,a.mobile_phone mobilePhone,a.qq,a.username, " +
            "d.name as 'departmentName',r.role from admin a LEFT join department d on a.department_id=d.id LEFT JOIN admin_role r on a.role_id=r.id WHERE a.id=:adminId ";
    Query query = em.createNativeQuery(sql);
    //设置结果转成Map类型
    query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    Object object = query.setParameter("adminId", id).getSingleResult();
    Map map = (HashMap) object;
    return map;
}
 
Example #25
Source Project: web-flash   Author: enilu   File: BaseRepositoryImpl.java    License: MIT License 5 votes vote down vote up
@Override
public List<Map> queryBySql(String sql) {
    Query query = entityManager.createNativeQuery(sql);
    query.unwrap(NativeQueryImpl.class)
            .setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    List list = query.getResultList();
    return list;
}
 
Example #26
Source Project: google-cloud-spanner-hibernate   Author: GoogleCloudPlatform   File: SQLTest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
@Test
public void test_sql_hibernate_dto_query_example() {
  doInJPA(this::entityManagerFactory, entityManager -> {
    Session session = entityManager.unwrap(Session.class);
    //tag::sql-hibernate-dto-query-example[]
    List<PersonSummaryDTO> dtos = session.createNativeQuery(
        "SELECT p.id as id, p.name as name " +
            "FROM Person p")
        .setResultTransformer(Transformers.aliasToBean(PersonSummaryDTO.class))
        .list();
    //end::sql-hibernate-dto-query-example[]
    assertEquals(3, dtos.size());
  });
}
 
Example #27
Source Project: ZTuoExchange_framework   Author: homeyanmi   File: MemberPromotionService.java    License: MIT License 5 votes vote down vote up
public Page<RegisterPromotionVO> getPromotionDetails(long memberId, PageModel pageModel){

        StringBuilder headSql = new StringBuilder("select a.id id ,a.username presentee,a.email presenteeEmail, ")
                .append("a.mobile_phone presenteePhone,a.real_name presenteeRealName,a.registration_time promotionTime, ")
                .append("b.level promotionLevel ") ;

        StringBuilder endSql = new StringBuilder(" from member a join member_promotion b on a.inviter_id = b.inviter_id and a.inviter_id = "+memberId);

        StringBuilder countHead = new StringBuilder("select count(*) ") ;
        Page<RegisterPromotionVO> page = createNativePageQuery(countHead.append(endSql),headSql.append(endSql),pageModel,Transformers.aliasToBean(RegisterPromotionVO.class)) ;
        RewardPromotionSetting setting = rewardPromotionSettingService.findByType(PromotionRewardType.REGISTER) ;

        BigDecimal one = JSONObject.parseObject(setting.getInfo()).getBigDecimal("one");
        BigDecimal two = JSONObject.parseObject(setting.getInfo()).getBigDecimal("two");

        for(RegisterPromotionVO vo:page.getContent()){
            vo.setUnit(setting.getCoin().getUnit());
            if(vo.getPromotionLevel()== PromotionLevel.ONE.getOrdinal()){
                vo.setReward(one);
            }else if(vo.getPromotionLevel()== PromotionLevel.TWO.getOrdinal()){
                vo.setReward(two);
            }else{
                vo.setReward(BigDecimal.ZERO);
            }
        }
        return page ;
    }
 
Example #28
Source Project: ZTuoExchange_framework   Author: homeyanmi   File: OrderService.java    License: MIT License 5 votes vote down vote up
public Map getOrderBySn(Long memberId, String orderSn) {
    String sql = "select o.*,m.real_name from otc_order o  join member m on o.customer_id=m.id and o.member_id=:memberId and o.order_sn =:orderSn ";
    Query query = em.createNativeQuery(sql);
    //设置结果转成Map类型
    query.unwrap(SQLQuery.class).setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    Object object = query.setParameter("memberId", memberId).setParameter("orderSn", orderSn).getSingleResult();
    Map map = (HashMap) object;
    return map;
}
 
Example #29
Source Project: JgFramework   Author: bupt1987   File: BaseDao.java    License: Apache License 2.0 5 votes vote down vote up
protected SQLQuery getQuery(String queryString, Map<String, Object> where, int start, int limit, boolean returnMap) {
    Session session = this.getSession();
    SQLQuery query = null;
    if (start > -1 && limit > 0) {
        query = session.createSQLQuery(queryString);
        query.setFirstResult(start);
        query.setMaxResults(limit);
    } else {
        query = session.createSQLQuery(queryString);
    }
    if (where != null) {
        for (Entry<String, Object> entry : where.entrySet()) {
            Object value = entry.getValue();
            String key = entry.getKey();
            if (value instanceof Collection) {
                query.setParameterList(key, (Collection) value);
            } else if (value instanceof Object[]) {
                query.setParameterList(key, (Object[]) value);
            } else {
                query.setParameter(key, value);
            }
        }
    }
    if (returnMap) {
        query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
    }
    return query;
}
 
Example #30
Source Project: oim-fx   Author: oimchat   File: BaseAbstractDAO.java    License: MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> List<T> queryList(String queryString, QueryWrapper queryWrapper, Class<T> resultClass, List<ResultType> returnTypeList) {

	Session session = sessionBox.getCurrentSession();
	List<T> list = null;

	Query query = createSQLQuery(session, queryString);
	setParameter(query, queryWrapper);
	if (null != returnTypeList) {
		setScalar(query, returnTypeList);
	}
	if (resultClass != null && !this.isPrimitive(resultClass) && !this.isString(resultClass)) {
		if (null == returnTypeList || returnTypeList.isEmpty()) {
			query.setResultTransformer(new ResultToBean(resultClass));
		} else {
			query.setResultTransformer(Transformers.aliasToBean(resultClass));
		}
	}

	if (null == resultClass) {
		query.setResultTransformer(new ResultToBean(resultClass));
	}

	list = query.list();
	if (null == list) {
		list = new ArrayList<>();
	}
	return list;
}