use of javax.persistence.TupleElement in project hibernate-orm by hibernate.
the class TupleQueryTest method testGetAlias.
@Test
public void testGetAlias() {
EntityManager em = getOrCreateEntityManager();
try {
em.getTransaction().begin();
User u = new User("Fab");
em.persist(u);
em.getTransaction().commit();
TypedQuery<Tuple> query = em.createQuery("SELECT u.firstName as fn from User u", Tuple.class);
List<Tuple> result = query.getResultList();
List<TupleElement<?>> elements = result.get(0).getElements();
assertThat(elements.size(), is(1));
final String alias = elements.get(0).getAlias();
assertThat(alias, is("fn"));
} catch (Exception e) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
throw e;
} finally {
em.close();
}
}
use of javax.persistence.TupleElement in project hibernate-orm by hibernate.
the class TupleQueryTest method testGetAliasReturnNullIfNoAliasExist.
@Test
public void testGetAliasReturnNullIfNoAliasExist() {
EntityManager em = getOrCreateEntityManager();
try {
em.getTransaction().begin();
User u = new User("Fab");
em.persist(u);
em.getTransaction().commit();
TypedQuery<Tuple> query = em.createQuery("SELECT u.firstName from User u", Tuple.class);
List<Tuple> result = query.getResultList();
List<TupleElement<?>> elements = result.get(0).getElements();
assertThat(elements.size(), is(1));
final String alias = elements.get(0).getAlias();
assertThat(alias, is(nullValue()));
} catch (Exception e) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
throw e;
} finally {
em.close();
}
}
use of javax.persistence.TupleElement in project tests by datanucleus.
the class JPQLQueryTest method testResultClassViaTuple.
public void testResultClassViaTuple() {
try {
EntityManager em = getEM();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
Person p1 = new Person(101, "Fred", "Flintstone", "fred.flintstone@jpox.com");
em.persist(p1);
em.flush();
TypedQuery<Tuple> q = em.createQuery("SELECT T.firstName,T.lastName FROM " + Person.class.getName() + " T", Tuple.class);
List<Tuple> results = q.getResultList();
assertNotNull("Returned object was null!", results);
assertEquals(1, results.size());
Tuple result = results.get(0);
List<TupleElement<?>> resultElems = result.getElements();
assertEquals(2, resultElems.size());
assertEquals("firstName", resultElems.get(0).getAlias());
assertEquals("lastName", resultElems.get(1).getAlias());
Object val0 = result.get(0);
assertEquals("Fred", val0);
Object val1 = result.get(1);
assertEquals("Flintstone", val1);
} catch (NoResultException ex) {
// expected
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
} finally {
clean(Person.class);
}
}
use of javax.persistence.TupleElement in project microservices by pwillhan.
the class Projection method executeQueries.
@Test
public void executeQueries() throws Exception {
TestDataCategoriesItems testData = storeTestData();
CriteriaBuilder cb = JPA.getEntityManagerFactory().getCriteriaBuilder();
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager();
{
// Product
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
Root<Bid> b = criteria.from(Bid.class);
criteria.select(cb.tuple(i, b));
/* Convenient alternative:
criteria.multiselect(
criteria.from(Item.class),
criteria.from(Bid.class)
);
*/
Query q = em.createQuery(criteria);
List<Object[]> result = q.getResultList();
// Cartesian product!
assertEquals(result.size(), 12);
Set<Item> items = new HashSet();
Set<Bid> bids = new HashSet();
for (Object[] row : result) {
assertTrue(row[0] instanceof Item);
items.add((Item) row[0]);
assertTrue(row[1] instanceof Bid);
bids.add((Bid) row[1]);
}
assertEquals(items.size(), 3);
assertEquals(bids.size(), 4);
}
em.clear();
{
// Transient result
CriteriaQuery criteria = cb.createQuery();
Root<User> u = criteria.from(User.class);
// Returns List of Object[]
criteria.multiselect(u.get("id"), u.get("username"), u.get("homeAddress"));
Query q = em.createQuery(criteria);
List<Object[]> result = q.getResultList();
assertEquals(result.size(), 3);
Object[] firstRow = result.get(0);
assertTrue(firstRow[0] instanceof Long);
assertTrue(firstRow[1] instanceof String);
assertTrue(firstRow[2] instanceof Address);
}
em.clear();
{
// Distinct
CriteriaQuery<String> criteria = cb.createQuery(String.class);
criteria.select(criteria.from(Item.class).<String>get("name"));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 3);
}
em.clear();
{
// Distinct
CriteriaQuery<String> criteria = cb.createQuery(String.class);
criteria.select(criteria.from(Item.class).<String>get("name"));
criteria.distinct(true);
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 3);
}
em.clear();
{
// Dynamic instance creation
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.select(cb.construct(// Must have the right constructor!
ItemSummary.class, i.get("id"), i.get("name"), i.get("auctionEnd")));
Query q = em.createQuery(criteria);
List<ItemSummary> result = q.getResultList();
assertEquals(result.size(), 3);
}
em.clear();
{
// Tuple API
CriteriaQuery<Tuple> criteria = cb.createTupleQuery();
// Or: CriteriaQuery<Tuple> criteria = cb.createQuery(Tuple.class);
criteria.multiselect(// Aliases optional!
criteria.from(Item.class).alias("i"), criteria.from(Bid.class).alias("b"));
TypedQuery<Tuple> query = em.createQuery(criteria);
List<Tuple> result = query.getResultList();
Set<Item> items = new HashSet();
Set<Bid> bids = new HashSet();
for (Tuple tuple : result) {
// Indexed
Item item = tuple.get(0, Item.class);
Bid bid = tuple.get(1, Bid.class);
// Alias
item = tuple.get("i", Item.class);
bid = tuple.get("b", Bid.class);
// Meta
for (TupleElement<?> element : tuple.getElements()) {
Class clazz = element.getJavaType();
String alias = element.getAlias();
Object value = tuple.get(element);
}
items.add(item);
bids.add(bid);
}
// Cartesian product!
assertEquals(result.size(), 12);
assertEquals(items.size(), 3);
assertEquals(bids.size(), 4);
}
em.clear();
// All following are more function call examples, with variations
{
// Concat
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.select(cb.concat(cb.concat(i.<String>get("name"), ":"), // Note the cast of Date!
i.<String>get("auctionEnd")));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 3);
}
em.clear();
{
// Coalesce
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.multiselect(i.get("name"), cb.coalesce(i.<BigDecimal>get("buyNowPrice"), 0));
Query q = em.createQuery(criteria);
List<Object[]> result = q.getResultList();
assertEquals(result.size(), 3);
for (Object[] row : result) {
assertTrue(row[0] instanceof String);
// Never NULL!
assertTrue(row[1] instanceof BigDecimal);
}
}
em.clear();
{
// Case When
/*
CriteriaQuery criteria = cb.createQuery();
TODO String literals not supported, Hibernate bug HHH-8124
Root<User> u = criteria.from(User.class);
criteria.multiselect(
u.get("username"),
cb.selectCase()
.when(
cb.equal(
cb.length(u.get("homeAddress").<String>get("zipcode")), 5
), "Germany"
)
.when(
cb.equal(
cb.length(u.get("homeAddress").<String>get("zipcode")), 4
), "Switzerland"
)
.otherwise("Other")
);
Query q = em.createQuery(criteria);
List<Object[]> result = q.getResultList();
assertEquals(result.size(), 3);
for (Object[] row : result) {
assertTrue(row[0] instanceof String);
assertTrue(row[1] instanceof String);
}
*/
}
em.clear();
{
// Count
CriteriaQuery criteria = cb.createQuery();
criteria.select(cb.count(criteria.from(Item.class)));
Query q = em.createQuery(criteria);
Long count = (Long) q.getSingleResult();
assertEquals(count, new Long(3));
}
em.clear();
{
// count(distinct ...)
CriteriaQuery criteria = cb.createQuery();
criteria.select(cb.countDistinct(criteria.from(Item.class).get("name")));
Query q = em.createQuery(criteria);
Long count = (Long) q.getSingleResult();
assertEquals(count, new Long(3));
}
em.clear();
{
// Sum
CriteriaQuery<Number> criteria = cb.createQuery(Number.class);
criteria.select(cb.sum(criteria.from(Bid.class).<BigDecimal>get("amount")));
Query q = em.createQuery(criteria);
BigDecimal sum = (BigDecimal) q.getSingleResult();
assertEquals(sum.compareTo(new BigDecimal("304.99")), 0);
}
em.clear();
{
// Min/Max
CriteriaQuery criteria = cb.createQuery();
Root<Bid> b = criteria.from(Bid.class);
criteria.multiselect(cb.min(b.<BigDecimal>get("amount")), cb.max(b.<BigDecimal>get("amount")));
criteria.where(cb.equal(b.get("item").<Long>get("id"), cb.parameter(Long.class, "itemId")));
Query q = em.createQuery(criteria);
q.setParameter("itemId", testData.items.getFirstId());
Object[] result = (Object[]) q.getSingleResult();
assertEquals(((BigDecimal) result[0]).compareTo(new BigDecimal("99")), 0);
assertEquals(((BigDecimal) result[1]).compareTo(new BigDecimal("101")), 0);
}
em.clear();
tx.commit();
em.close();
} finally {
TM.rollback();
}
}
use of javax.persistence.TupleElement in project tests by datanucleus.
the class CriteriaMetaModelTest method testResultTuple.
/**
* Test basic querying with a result as a Tuple.
*/
public void testResultTuple() {
EntityManager em = getEM();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<Tuple> crit = cb.createTupleQuery();
Root<Manager> candidate = crit.from(Manager.class);
Set<Join<Manager, ?>> joins = candidate.getJoins();
// Make sure joins returns empty set
assertNotNull(joins);
assertEquals(0, joins.size());
Set<Fetch<Manager, ?>> fetches = candidate.getFetches();
// Make sure fetches returns empty set
assertNotNull(fetches);
assertEquals(0, fetches.size());
candidate.alias("m");
crit.multiselect(candidate.get(Manager_.firstName), candidate.get(Manager_.lastName));
// DN extension
assertEquals("Generated JPQL query is incorrect", "SELECT m.firstName,m.lastName FROM org.datanucleus.samples.jpa.query.Manager m", crit.toString());
Query q = em.createQuery(crit);
List<Tuple> results = q.getResultList();
assertNotNull("Null results returned!", results);
assertEquals("Number of results is incorrect", 2, results.size());
boolean mourinho = false;
boolean guardiola = false;
Iterator<Tuple> resultIter = results.iterator();
while (resultIter.hasNext()) {
Tuple result = resultIter.next();
List<TupleElement<?>> tupleElements = result.getElements();
assertEquals(2, tupleElements.size());
Object elem0 = result.get(0);
Object elem1 = result.get(1);
assertTrue(elem0 instanceof String);
assertTrue(elem1 instanceof String);
String first = (String) elem0;
String last = (String) elem1;
if (first.equals("Jose") && last.equals("Mourinho")) {
mourinho = true;
} else if (first.equals("Pep") && last.equals("Guardiola")) {
guardiola = true;
}
}
if (!mourinho) {
fail("Jose Mourinho not returned");
}
if (!guardiola) {
fail("Pep Guardiola not returned");
}
tx.rollback();
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
Aggregations