use of org.jpwh.model.querying.User in project microservices by pwillhan.
the class Restriction 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();
{
// select i from Item i where i.name = 'Foo'
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.select(i).where(cb.equal(i.get("name"), "Foo"));
TypedQuery<Item> q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 1);
assertEquals(q.getResultList().iterator().next().getName(), "Foo");
}
em.clear();
{
// Equals boolean
CriteriaQuery criteria = cb.createQuery();
Root<User> u = criteria.from(User.class);
criteria.select(u).where(cb.equal(u.get("activated"), true));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 2);
}
em.clear();
{
// Between
CriteriaQuery criteria = cb.createQuery();
Root<Bid> b = criteria.from(Bid.class);
criteria.select(b).where(cb.between(// Type of path required!
b.<BigDecimal>get("amount"), // Must be same type!
new BigDecimal("99"), // Must be same type!
new BigDecimal("110")));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 3);
}
em.clear();
{
// Greater than
CriteriaQuery criteria = cb.createQuery();
Root<Bid> b = criteria.from(Bid.class);
criteria.select(b).where(// gt() only works with Number, use greaterThan() otherwise!
cb.gt(b.<BigDecimal>get("amount"), new BigDecimal("100")));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 1);
}
em.clear();
{
// Greater than with date (!Number)
Date tomorrowDate = CalendarUtil.TOMORROW.getTime();
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.select(i).where(cb.greaterThan(i.<Date>get("auctionEnd"), tomorrowDate));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 1);
}
em.clear();
{
// IN list
CriteriaQuery criteria = cb.createQuery();
Root<User> u = criteria.from(User.class);
criteria.select(u).where(cb.<String>in(u.<String>get("username")).value("johndoe").value("janeroe"));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 2);
}
em.clear();
{
// Enum
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.select(i).where(cb.equal(i.<AuctionType>get("auctionType"), AuctionType.HIGHEST_BID));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 3);
}
em.clear();
{
// Ternary operators
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.select(i).where(cb.isNull(i.get("buyNowPrice")));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 2);
}
em.clear();
{
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.select(i).where(cb.isNotNull(i.get("buyNowPrice")));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 1);
}
em.clear();
{
// String matching
CriteriaQuery criteria = cb.createQuery();
Root<User> u = criteria.from(User.class);
criteria.select(u).where(cb.like(u.<String>get("username"), "john%"));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 1);
}
{
// String matching
CriteriaQuery criteria = cb.createQuery();
Root<User> u = criteria.from(User.class);
criteria.select(u).where(cb.like(u.<String>get("username"), "john%").not());
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 2);
}
em.clear();
{
CriteriaQuery criteria = cb.createQuery();
Root<User> u = criteria.from(User.class);
criteria.select(u).where(cb.like(u.<String>get("username"), "%oe%"));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 3);
}
em.clear();
{
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.select(i).where(cb.like(i.<String>get("name"), "Name\\_with\\_underscores", '\\'));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 0);
}
em.clear();
{
// Arithmetic
CriteriaQuery criteria = cb.createQuery();
Root<Bid> b = criteria.from(Bid.class);
criteria.select(b).where(cb.gt(cb.diff(cb.quot(b.<BigDecimal>get("amount"), 2), 0.5), 49));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 2);
}
em.clear();
{
// Logical groups
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
Predicate predicate = cb.and(cb.like(i.<String>get("name"), "Fo%"), cb.isNotNull(i.get("buyNowPrice")));
predicate = cb.or(predicate, cb.equal(i.<String>get("name"), "Bar"));
criteria.select(i).where(predicate);
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 2);
}
em.clear();
{
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.select(i).where(cb.like(i.<String>get("name"), "Fo%"), // AND
cb.isNotNull(i.get("buyNowPrice")));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 1);
}
em.clear();
{
// Collection functions
CriteriaQuery criteria = cb.createQuery();
Root<Category> c = criteria.from(Category.class);
criteria.select(c).where(cb.isNotEmpty(c.<Collection>get("items")));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 2);
}
em.clear();
{
// Collection functions
CriteriaQuery criteria = cb.createQuery();
Root<Category> c = criteria.from(Category.class);
criteria.select(c).where(cb.isMember(cb.parameter(Item.class, "item"), c.<Collection<Item>>get("items")));
Query q = em.createQuery(criteria);
Item item = em.find(Item.class, testData.items.getFirstId());
q.setParameter("item", item);
List<Category> result = q.getResultList();
assertEquals(result.size(), 1);
}
em.clear();
{
// Collection functions
CriteriaQuery criteria = cb.createQuery();
Root<Category> c = criteria.from(Category.class);
criteria.select(c).where(cb.gt(cb.size(c.<Collection>get("items")), 1));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 1);
}
em.clear();
{
// Calling functions
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.select(i).where(cb.like(cb.lower(i.<String>get("name")), "ba%"));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 2);
}
em.clear();
{
// Ordering result
CriteriaQuery criteria = cb.createQuery();
Root<User> u = criteria.from(User.class);
criteria.select(u).orderBy(cb.desc(u.get("username")));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 3);
}
em.clear();
{
// Ordering result
CriteriaQuery criteria = cb.createQuery();
Root<User> u = criteria.from(User.class);
criteria.select(u).orderBy(cb.desc(u.get("activated")), cb.asc(u.get("username")));
Query q = em.createQuery(criteria);
assertEquals(q.getResultList().size(), 3);
}
tx.commit();
em.close();
} finally {
TM.rollback();
}
}
use of org.jpwh.model.querying.User in project microservices by pwillhan.
the class Typesafe 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();
{
// Typesafe path navigation
CriteriaQuery<User> criteria = cb.createQuery(User.class);
Root<User> u = criteria.from(User.class);
criteria.select(u).where(cb.equal(u.get(User_.homeAddress).get(Address_.city), "Some City"));
TypedQuery<User> q = em.createQuery(criteria);
User user = q.getSingleResult();
assertEquals(user.getId(), testData.users.getFirstId());
}
em.clear();
{
// Typesafe operands for joins and restriction
CriteriaQuery<Item> criteria = cb.createQuery(Item.class);
Root<Item> i = criteria.from(Item.class);
Join<Item, Bid> b = i.join(Item_.bids);
criteria.select(i).where(cb.gt(b.get(Bid_.amount), new BigDecimal(100)));
// cb.gt(b.get(Bid_.amount), "100")); // Wouldn't compile!
TypedQuery<Item> q = em.createQuery(criteria);
List<Item> result = q.getResultList();
assertEquals(result.size(), 1);
assertEquals(result.get(0).getId(), testData.items.getFirstId());
}
em.clear();
tx.commit();
em.close();
} finally {
TM.rollback();
}
}
use of org.jpwh.model.querying.User in project microservices by pwillhan.
the class Subselects method executeQueries.
@Test
public void executeQueries() throws Exception {
TestDataCategoriesItems testData = storeTestData();
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager();
{
Query q = em.createNamedQuery("correlated");
List<User> result = q.getResultList();
assertEquals(result.size(), 1);
User user = result.iterator().next();
assertEquals(user.getId(), testData.users.getFirstId());
}
em.clear();
{
Query q = em.createNamedQuery("uncorrelated");
List<Bid> result = q.getResultList();
assertEquals(result.size(), 2);
}
{
Query q = em.createNamedQuery("exists");
List<Item> result = q.getResultList();
assertEquals(result.size(), 2);
}
em.clear();
{
Query q = em.createNamedQuery("quantifyAll");
List<Item> result = q.getResultList();
assertEquals(result.size(), 2);
}
em.clear();
{
Query q = em.createNamedQuery("quantifyAny");
List<Item> result = q.getResultList();
assertEquals(result.size(), 1);
}
em.clear();
tx.commit();
em.close();
} finally {
TM.rollback();
}
}
use of org.jpwh.model.querying.User in project microservices by pwillhan.
the class FilterCollections method executeQueries.
@Test
public void executeQueries() throws Exception {
TestDataCategoriesItems testData = storeTestData();
Long ITEM_ID = testData.items.getFirstId();
Long USER_ID = testData.users.getLastId();
UserTransaction tx = TM.getUserTransaction();
try {
tx.begin();
EntityManager em = JPA.createEntityManager();
Session session = em.unwrap(Session.class);
{
// Filter the bids by bidder, order by amount descending
Item item = em.find(Item.class, ITEM_ID);
User user = em.find(User.class, USER_ID);
org.hibernate.Query query = session.createFilter(item.getBids(), "where this.bidder = :bidder order by this.amount desc");
query.setParameter("bidder", user);
List<Bid> bids = query.list();
assertEquals(bids.size(), 3);
assertEquals(bids.get(0).getBidder(), user);
assertEquals(bids.get(0).getAmount().compareTo(new BigDecimal("101")), 0);
assertEquals(bids.get(1).getAmount().compareTo(new BigDecimal("100")), 0);
assertEquals(bids.get(2).getAmount().compareTo(new BigDecimal("99")), 0);
}
em.clear();
{
// Retrieve a page of bids
Item item = em.find(Item.class, ITEM_ID);
org.hibernate.Query query = session.createFilter(item.getBids(), "");
// Retrieve only two bids
query.setFirstResult(0);
query.setMaxResults(2);
List<Bid> bids = query.list();
assertEquals(bids.size(), 2);
}
em.clear();
{
// Retrieve items sold by bidders on this item
Item item = em.find(Item.class, ITEM_ID);
org.hibernate.Query query = session.createFilter(item.getBids(), "from Item i where i.seller = this.bidder");
List<Item> items = query.list();
assertEquals(items.size(), 0);
}
em.clear();
{
// Retrieve users who have bid on the item
Item item = em.find(Item.class, ITEM_ID);
org.hibernate.Query query = session.createFilter(item.getBids(), "select distinct this.bidder.username order by this.bidder.username asc");
List<String> bidders = query.list();
assertEquals(bidders.size(), 1);
assertEquals(bidders.get(0), "robertdoe");
}
em.clear();
{
// Limit the bids to greater or equal than 100
Item item = em.find(Item.class, ITEM_ID);
org.hibernate.Query query = session.createFilter(item.getBids(), "where this.amount >= :param");
query.setParameter("param", new BigDecimal(100));
List<Bid> bids = query.list();
assertEquals(bids.size(), 2);
}
em.clear();
tx.commit();
em.close();
} finally {
TM.rollback();
}
}
use of org.jpwh.model.querying.User 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