use of javax.persistence.criteria.Fetch in project hibernate-orm by hibernate.
the class QueryStructure method renderFetches.
@SuppressWarnings({ "unchecked" })
private void renderFetches(StringBuilder jpaqlQuery, RenderingContext renderingContext, Collection<Fetch> fetches) {
if (fetches == null) {
return;
}
for (Fetch fetch : fetches) {
((FromImplementor) fetch).prepareAlias(renderingContext);
jpaqlQuery.append(renderJoinType(fetch.getJoinType())).append("fetch ").append(((FromImplementor) fetch).renderTableExpression(renderingContext));
renderFetches(jpaqlQuery, renderingContext, fetch.getFetches());
}
}
use of javax.persistence.criteria.Fetch in project microservices by pwillhan.
the class Joins 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();
{
// Implicit inner join
CriteriaQuery criteria = cb.createQuery();
Root<Bid> b = criteria.from(Bid.class);
criteria.select(b).where(cb.like(b.get("item").<String>get("name"), "Fo%"));
Query q = em.createQuery(criteria);
List<Bid> result = q.getResultList();
assertEquals(result.size(), 3);
for (Bid bid : result) {
assertEquals(bid.getItem().getId(), testData.items.getFirstId());
}
}
em.clear();
{
// Multiple inner
CriteriaQuery<Bid> criteria = cb.createQuery(Bid.class);
Root<Bid> b = criteria.from(Bid.class);
criteria.select(b).where(cb.equal(b.get("item").get("seller").get("username"), "johndoe"));
Query q = em.createQuery(criteria);
List<Bid> result = q.getResultList();
assertEquals(result.size(), 4);
}
em.clear();
{
// Multiple inner
CriteriaQuery criteria = cb.createQuery();
Root<Bid> b = criteria.from(Bid.class);
criteria.select(b).where(cb.and(cb.equal(b.get("item").get("seller").get("username"), "johndoe"), cb.isNotNull(b.get("item").get("buyNowPrice"))));
Query q = em.createQuery(criteria);
List<Bid> result = q.getResultList();
assertEquals(result.size(), 3);
}
em.clear();
{
// Explicit inner
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
Join<Item, Bid> b = i.join("bids");
criteria.select(i).where(cb.gt(b.<BigDecimal>get("amount"), new BigDecimal(100)));
Query q = em.createQuery(criteria);
List<Item> result = q.getResultList();
assertEquals(result.size(), 1);
assertEquals(result.get(0).getId(), testData.items.getFirstId());
}
em.clear();
{
// Explicit outer
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
Join<Item, Bid> b = i.join("bids", JoinType.LEFT);
b.on(cb.gt(b.<BigDecimal>get("amount"), new BigDecimal(100)));
criteria.multiselect(i, b);
Query q = em.createQuery(criteria);
List<Object[]> result = q.getResultList();
assertEquals(result.size(), 3);
assertTrue(result.get(0)[0] instanceof Item);
assertTrue(result.get(0)[1] instanceof Bid);
assertTrue(result.get(1)[0] instanceof Item);
assertEquals(result.get(1)[1], null);
assertTrue(result.get(2)[0] instanceof Item);
assertEquals(result.get(2)[1], null);
}
em.clear();
{
// Explicit right outer
/* TODO Right outer joins not supported in criteria, Hibernate bug JPA-2
CriteriaQuery criteria = cb.createQuery();
Root<Bid> b = criteria.from(Bid.class);
Join<Bid, Item> i = b.join("item", JoinType.RIGHT);
criteria.multiselect(b, i).where(
cb.or(
cb.isNull(b),
cb.gt(b.<BigDecimal>get("amount"), new BigDecimal(100)))
);
Query q = em.createQuery(criteria);
List<Object[]> result = q.getResultList();
assertEquals(result.size(), 2);
assertTrue(result.get(0)[0] instanceof Bid);
assertTrue(result.get(0)[1] instanceof Item);
assertEquals(result.get(1)[0], null);
assertTrue(result.get(1)[1] instanceof Item);
*/
}
em.clear();
{
// A typical "fetch the bids collections for all items as a side effect" query
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
i.fetch("bids", JoinType.LEFT);
criteria.select(i);
Query q = em.createQuery(criteria);
List<Item> result = q.getResultList();
// 3 items, 4 bids, 5 "rows" in result!
assertEquals(result.size(), 5);
// In-memory "distinct"
Set<Item> distinctResult = new LinkedHashSet<Item>(result);
// It was only three items all along...
assertEquals(distinctResult.size(), 3);
boolean haveBids = false;
for (Item item : distinctResult) {
// No more lazy loading!
em.detach(item);
if (item.getBids().size() > 0) {
haveBids = true;
break;
}
}
assertTrue(haveBids);
}
em.clear();
{
// Hibernate can remove the duplicate SQL resultset rows for you
// (...who knows, some of you actually WANT the duplicates!)
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
i.fetch("bids", JoinType.LEFT);
criteria.select(i).distinct(true);
Query q = em.createQuery(criteria);
List<Item> result = q.getResultList();
// Hibernate filtered it for us in-memory
assertEquals(result.size(), 3);
boolean haveBids = false;
for (Item item : result) {
// No more lazy loading!
em.detach(item);
if (item.getBids().size() > 0) {
haveBids = true;
break;
}
}
assertTrue(haveBids);
}
em.clear();
{
// Fetch multiple associated instances/collections
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
Fetch<Item, Bid> b = i.fetch("bids", JoinType.LEFT);
// These are non-nullable foreign key columns, inner join or
b.fetch("bidder");
// outer doesn't make a difference!
i.fetch("seller", JoinType.LEFT);
criteria.select(i).distinct(true);
Query q = em.createQuery(criteria);
List<Item> result = q.getResultList();
assertEquals(result.size(), 2);
boolean haveBids = false;
boolean haveBidder = false;
boolean haveSeller = false;
for (Item item : result) {
// No more lazy loading!
em.detach(item);
if (item.getBids().size() > 0) {
haveBids = true;
Bid bid = item.getBids().iterator().next();
if (bid.getBidder() != null && bid.getBidder().getUsername() != null) {
haveBidder = true;
}
}
if (item.getSeller() != null && item.getSeller().getUsername() != null)
haveSeller = true;
}
assertTrue(haveBids);
assertTrue(haveBidder);
assertTrue(haveSeller);
}
em.clear();
{
// SQL Cartesian product of multiple collections! Bad!
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
i.fetch("bids", JoinType.LEFT);
// Cartesian product, bad!
i.fetch("images", JoinType.LEFT);
criteria.select(i).distinct(true);
Query q = em.createQuery(criteria);
List<Item> result = q.getResultList();
assertEquals(result.size(), 3);
boolean haveBids = false;
boolean haveImages = false;
for (Item item : result) {
// No more lazy loading!
em.detach(item);
if (item.getBids().size() > 0)
haveBids = true;
if (item.getImages().size() > 0)
haveImages = true;
}
assertTrue(haveBids);
assertTrue(haveImages);
}
em.clear();
{
// Theta style inner join
CriteriaQuery criteria = cb.createQuery();
Root<User> u = criteria.from(User.class);
Root<LogRecord> log = criteria.from(LogRecord.class);
criteria.where(cb.equal(u.get("username"), log.get("username")));
criteria.multiselect(u, log);
Query q = em.createQuery(criteria);
List<Object[]> result = q.getResultList();
for (Object[] row : result) {
assertTrue(row[0] instanceof User);
assertTrue(row[1] instanceof LogRecord);
}
assertEquals(result.size(), 2);
}
em.clear();
{
// Theta style inner join, multiple
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
Root<Bid> b = criteria.from(Bid.class);
criteria.where(cb.equal(b.get("item"), i), cb.equal(i.get("seller"), b.get("bidder")));
criteria.multiselect(i, b);
Query q = em.createQuery(criteria);
List<Object[]> result = q.getResultList();
assertEquals(result.size(), 0);
}
em.clear();
{
// Inner join with implicit ID comparison
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
Root<User> u = criteria.from(User.class);
criteria.where(cb.equal(i.get("seller"), u), cb.like(u.<String>get("username"), "j%"));
criteria.multiselect(i, u);
Query q = em.createQuery(criteria);
List<Object[]> result = q.getResultList();
assertEquals(result.size(), 3);
for (Object[] row : result) {
assertTrue(row[0] instanceof Item);
assertTrue(row[1] instanceof User);
}
}
em.clear();
{
// Inner join with explicit ID comparison
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
Root<User> u = criteria.from(User.class);
criteria.where(cb.equal(i.get("seller").get("id"), u.get("id")), cb.like(u.<String>get("username"), "j%"));
criteria.multiselect(i, u);
Query q = em.createQuery(criteria);
List<Object[]> result = q.getResultList();
assertEquals(result.size(), 3);
for (Object[] row : result) {
assertTrue(row[0] instanceof Item);
assertTrue(row[1] instanceof User);
}
}
em.clear();
{
// Binding an entity parameter
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.where(cb.equal(i.get("seller"), cb.parameter(User.class, "seller")));
criteria.select(i);
Query q = em.createQuery(criteria);
User someUser = em.find(User.class, testData.users.getFirstId());
q.setParameter("seller", someUser);
List<Item> result = q.getResultList();
assertEquals(result.size(), 2);
}
em.clear();
{
// Binding ID parameter
CriteriaQuery criteria = cb.createQuery();
Root<Item> i = criteria.from(Item.class);
criteria.where(cb.equal(i.get("seller").get("id"), cb.parameter(Long.class, "sellerId")));
criteria.select(i);
Query q = em.createQuery(criteria);
Long USER_ID = testData.users.getFirstId();
q.setParameter("sellerId", USER_ID);
List<Item> result = q.getResultList();
assertEquals(result.size(), 2);
}
em.clear();
{
// Not a join, just ID comparison
CriteriaQuery<Bid> criteria = cb.createQuery(Bid.class);
Root<Bid> b = criteria.from(Bid.class);
criteria.where(cb.equal(b.get("item").get("id"), cb.parameter(Long.class, "itemId")));
criteria.select(b);
Query q = em.createQuery(criteria);
q.setParameter("itemId", testData.items.getFirstId());
List<Bid> result = q.getResultList();
assertEquals(result.size(), 3);
}
em.clear();
tx.commit();
em.close();
} finally {
TM.rollback();
}
}
use of javax.persistence.criteria.Fetch in project stdlib by petergeneric.
the class JPAQueryBuilder method addFetches.
private void addFetches(Collection<String> fetches) {
Map<String, Fetch> created = new HashMap<>();
for (String fetch : fetches) {
Fetch parent = null;
final String[] parts = StringUtils.split(fetch, '.');
for (int i = 0; i < parts.length; i++) {
final String path = StringUtils.join(parts, '.', 0, i + 1);
Fetch existing = created.get(path);
if (existing == null) {
if (parent == null) {
// attribute of root
existing = root.fetch(parts[i], JoinType.LEFT);
} else {
// attribute of parent
existing = parent.fetch(parts[i], JoinType.LEFT);
}
created.put(path, existing);
}
parent = existing;
}
}
}
use of javax.persistence.criteria.Fetch in project tests by datanucleus.
the class CriteriaMetaModelTest method testResultCase.
/**
* Test basic querying with a result including CASE expression.
*/
public void testResultCase() {
EntityManager em = getEM();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
CriteriaBuilder cb = emf.getCriteriaBuilder();
CriteriaQuery<Manager> crit = cb.createQuery(Manager.class);
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");
Path<Integer> yrsVar = candidate.get(Manager_.yearsExperience);
Predicate lessThan2 = cb.lessThan(yrsVar, 5);
crit.multiselect(candidate.get(Manager_.firstName), candidate.get(Manager_.lastName), cb.selectCase().when(lessThan2, "Junior").otherwise("Senior"));
// DN extension
assertEquals("Generated JPQL query is incorrect", "SELECT m.firstName,m.lastName,CASE WHEN (m.yearsExperience < 5) THEN 'Junior' ELSE 'Senior' END FROM org.datanucleus.samples.jpa.query.Manager m", crit.toString());
Query q = em.createQuery(crit);
List<Object[]> results = q.getResultList();
assertNotNull("Null results returned!", results);
assertEquals("Number of results is incorrect", 2, results.size());
boolean mourinho = false;
boolean guardiola = false;
Iterator<Object[]> resultIter = results.iterator();
while (resultIter.hasNext()) {
Object[] result = resultIter.next();
assertEquals(3, result.length);
if (result[0].equals("Jose") && result[1].equals("Mourinho")) {
mourinho = true;
assertEquals("Senior", result[2]);
} else if (result[0].equals("Pep") && result[1].equals("Guardiola")) {
guardiola = true;
assertEquals("Junior", result[2]);
}
}
if (!mourinho) {
fail("Jose Mourinho not returned");
}
if (!guardiola) {
fail("Pep Guardiola not returned");
}
tx.rollback();
} finally {
if (tx.isActive()) {
tx.rollback();
}
em.close();
}
}
use of javax.persistence.criteria.Fetch 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