use of org.hibernate.transform.ResultTransformer in project querydsl by querydsl.
the class HibernateHandler method transform.
@Override
public boolean transform(Query query, FactoryExpression<?> projection) {
try {
ResultTransformer transformer = new FactoryExpressionTransformer(projection);
query.unwrap(org.hibernate.query.Query.class).setResultTransformer(transformer);
return true;
} catch (PersistenceException e) {
return false;
}
}
use of org.hibernate.transform.ResultTransformer in project hibernate-orm by hibernate.
the class ResultTransformerTest method testResultTransformerIsAppliedToScrollableResults.
@Test
@TestForIssue(jiraKey = "HHH-3694")
public void testResultTransformerIsAppliedToScrollableResults() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
PartnerA a = new PartnerA();
a.setName("Partner A");
PartnerB b = new PartnerB();
b.setName("Partner B");
Contract obj1 = new Contract();
obj1.setName("Contract");
obj1.setA(a);
obj1.setB(b);
s.save(a);
s.save(b);
s.save(obj1);
tx.commit();
s.close();
s = openSession();
Query q = s.getNamedQuery(Contract.class.getName() + ".testQuery");
q.setFetchSize(100);
q.setResultTransformer(new ResultTransformer() {
private static final long serialVersionUID = -5815434828170704822L;
public Object transformTuple(Object[] arg0, String[] arg1) {
// return only the PartnerA object from the query
return arg0[1];
}
@SuppressWarnings("unchecked")
public List transformList(List arg0) {
return arg0;
}
});
ScrollableResults sr = q.scroll();
// does not support java.sql.ResultSet.first()
if (getDialect() instanceof AbstractHANADialect) {
sr.next();
} else {
sr.first();
}
Object[] row = sr.get();
assertEquals(1, row.length);
Object obj = row[0];
assertTrue(obj instanceof PartnerA);
PartnerA obj2 = (PartnerA) obj;
assertEquals("Partner A", obj2.getName());
s.close();
}
use of org.hibernate.transform.ResultTransformer in project hibernate-orm by hibernate.
the class AbstractQueryCacheResultTransformerTest method testMultiProjectionListThenApplyAliasToBean.
@Test
public void testMultiProjectionListThenApplyAliasToBean() throws Exception {
CriteriaExecutor criteriaExecutor = new CriteriaExecutor() {
protected Criteria getCriteria(Session s) {
return s.createCriteria(Enrolment.class, "e").createAlias("e.student", "st").createAlias("e.course", "co").setProjection(Projections.projectionList().add(Property.forName("st.name")).add(Property.forName("co.description"))).addOrder(Order.asc("e.studentNumber"));
}
};
HqlExecutor hqlExecutor = new HqlExecutor() {
public Query getQuery(Session s) {
return s.createQuery("select st.name as studentName, co.description as courseDescription from Enrolment e join e.student st join e.course co order by e.studentNumber");
}
};
ResultChecker checker = new ResultChecker() {
public void check(Object results) {
List resultList = (List) results;
ResultTransformer transformer = Transformers.aliasToBean(StudentDTO.class);
String[] aliases = new String[] { "studentName", "courseDescription" };
for (int i = 0; i < resultList.size(); i++) {
resultList.set(i, transformer.transformTuple((Object[]) resultList.get(i), aliases));
}
assertEquals(2, resultList.size());
StudentDTO dto = (StudentDTO) resultList.get(0);
assertEquals(courseExpected.getDescription(), dto.getDescription());
assertEquals(yogiExpected.getName(), dto.getName());
dto = (StudentDTO) resultList.get(1);
assertEquals(courseExpected.getDescription(), dto.getDescription());
assertEquals(shermanExpected.getName(), dto.getName());
}
};
runTest(hqlExecutor, criteriaExecutor, checker, false);
}
use of org.hibernate.transform.ResultTransformer in project hibernate-orm by hibernate.
the class CriteriaOrderByTest method testCriteriaOrderBy.
@Test
@TestForIssue(jiraKey = "HHH-7116")
public void testCriteriaOrderBy() {
final Session s = openSession();
final Transaction tx = s.beginTransaction();
Item item;
Bid bid;
item = new Item();
item.name = "ZZZZ";
s.persist(item);
bid = new Bid();
bid.amount = 444.44f;
bid.item = item;
s.persist(bid);
item = new Item();
item.name = "AAAA";
s.persist(item);
bid = new Bid();
bid.amount = 222.22f;
bid.item = item;
s.persist(bid);
item = new Item();
item.name = "MMMM";
s.persist(item);
bid = new Bid();
bid.amount = 999.99f;
bid.item = item;
s.persist(bid);
s.flush();
// For each item, ordered by name, show all bids made by bidders on this item.
// The joined collections item.bids and bidder.bids have orderings specified on the mappings.
// For some reason, the association mappings' ordering specifications are not honored if default (INNER) join
// type is used.
final Criteria criteria = s.createCriteria(Item.class).addOrder(org.hibernate.criterion.Order.asc("this.name")).createAlias("this.bids", "i_bid", JoinType.LEFT_OUTER_JOIN).setProjection(Projections.projectionList().add(Projections.property("this.name"), "item_name").add(Projections.property("i_bid.amount"), "bid_amount")).setResultTransformer(new ResultTransformer() {
boolean first = true;
Object[] previous;
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
if (first) {
first = false;
previous = tuple;
} else {
final String previousName = (String) previous[0];
final String name = (String) tuple[0];
Assert.assertTrue("The resultset tuples should be ordered by item name, as specified on the Criteria", previousName.compareTo(name) < 1);
previous = tuple;
}
return tuple;
}
@Override
public List transformList(List collection) {
return collection;
}
});
criteria.list();
tx.rollback();
s.close();
}
use of org.hibernate.transform.ResultTransformer in project microservices by pwillhan.
the class TransformResults method executeQueries.
@Test
public void executeQueries() throws Exception {
storeTestData();
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager();
Session session = em.unwrap(Session.class);
org.hibernate.Query query = session.createQuery("select i.id as itemId, i.name as name, i.auctionEnd as auctionEnd from Item i");
{
// Access List of Object[]
List<Object[]> result = query.list();
for (Object[] tuple : result) {
Long itemId = (Long) tuple[0];
String name = (String) tuple[1];
Date auctionEnd = (Date) tuple[2];
// ...
}
assertEquals(result.size(), 3);
}
em.clear();
{
// Transform to List of Lists
query.setResultTransformer(ToListResultTransformer.INSTANCE);
List<List> result = query.list();
for (List list : result) {
Long itemId = (Long) list.get(0);
String name = (String) list.get(1);
Date auctionEnd = (Date) list.get(2);
// ...
}
assertEquals(result.size(), 3);
}
em.clear();
{
// Transform to List of Maps
query.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<Map> result = query.list();
// You can access the aliases of the query
assertEquals(query.getReturnAliases(), new String[] { "itemId", "name", "auctionEnd" });
for (Map map : result) {
Long itemId = (Long) map.get("itemId");
String name = (String) map.get("name");
Date auctionEnd = (Date) map.get("auctionEnd");
// ...
}
assertEquals(result.size(), 3);
}
em.clear();
{
// Transform to List of Maps with entity aliases
org.hibernate.Query entityQuery = session.createQuery("select i as item, u as seller from Item i join i.seller u");
entityQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<Map> result = entityQuery.list();
for (Map map : result) {
Item item = (Item) map.get("item");
User seller = (User) map.get("seller");
assertEquals(item.getSeller(), seller);
// ...
}
assertEquals(result.size(), 3);
}
em.clear();
{
// Transform to List of JavaBean calling setters/fields
query.setResultTransformer(new AliasToBeanResultTransformer(ItemSummary.class));
List<ItemSummary> result = query.list();
for (ItemSummary itemSummary : result) {
Long itemId = itemSummary.getItemId();
String name = itemSummary.getName();
Date auctionEnd = itemSummary.getAuctionEnd();
// ...
}
assertEquals(result.size(), 3);
}
em.clear();
{
// Custom ResultTransformer
query.setResultTransformer(new ResultTransformer() {
/**
* For each result "row", an <code>Object[]</code> tuple has to be transformed into
* the desired result value for that row. Here you access each projection element by
* index in the tuple array, and then call the <code>ItemSummaryFactory</code> to produce
* the query result value. Hibernate passes the method the aliases found in the query, for each
* tuple element. You don't need the aliases in this transformer, though.
*/
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
Long itemId = (Long) tuple[0];
String name = (String) tuple[1];
Date auctionEnd = (Date) tuple[2];
// You can access the aliases of the query if needed
assertEquals(aliases[0], "itemId");
assertEquals(aliases[1], "name");
assertEquals(aliases[2], "auctionEnd");
return ItemSummaryFactory.newItemSummary(itemId, name, auctionEnd);
}
/**
* You can wrap or modify the result list after after transforming the tuples.
* Here you make the returned <code>List</code> unmodifiable,
* ideal for a reporting screen where nothing should change the data.
*/
@Override
public List transformList(List collection) {
// The "collection" is a List<ItemSummary>
return Collections.unmodifiableList(collection);
}
});
List<ItemSummary> result = query.list();
assertEquals(result.size(), 3);
}
em.clear();
/* Hibernate has an internal CriteriaResultTransformer for JPA criteria queries
TODO https://hibernate.atlassian.net/browse/HHH-8196
{
CriteriaBuilder cb = JPA.getEntityManagerFactory().getCriteriaBuilder();
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
i.alias("i");
criteria.multiselect(
i.get("id").alias("itemId"),
i.get("name").alias("name"),
i.get("auctionEnd").alias("auctionEnd")
);
Query query = em.createQuery(criteria);
org.hibernate.Query hibernateQuery = ((HibernateQuery)query).getHibernateQuery();
/*
assertEquals(
hibernateQuery.getQueryString(),
"select i.id as itemId, i.name as name, i.auctionEnd as auctionEnd from Item as i"
);
// Actual: select i.id, i.name, i.auctionEnd from Item as i
assertEquals(
hibernateQuery.getReturnAliases(),
new String[] {"itemId", "name", "auctionEnd"}
);
// Actual: 0, 1, 2
// Overrides the internal CriteriaResultTransformer, breaks JPA converters
hibernateQuery.setResultTransformer(
new AliasToBeanResultTransformer(ItemSummary.class)
);
List<ItemSummary> result = query.getResultList();
assertEquals(result.size(), 3);
}
em.clear();
*/
tx.commit();
em.close();
} finally {
TM.rollback();
}
}
Aggregations