How to fetch lazy collection in QueryDSL 4 - spring-boot

I have a following problem with executing quite simple query with querydsl. Imagine that we have two entities:
CAR ----< OWNERS
I would like to execute query which returns all cars and fetches all its owners which are mapped lazily. In other words, I would like to fetch those to be used outside of transaction.
My query looks like:
List<Car> cars = new JPAQuery<Car>(em)
.select(car).from(car)
.leftJoin(car.owners, owner)
.where(car.make.eq(make))
.orderBy(new OrderSpecifier<>(Order.ASC, car.id))
.distinct()
.fetch();
Similar query worked fine in QueryDSL 3, but after upgrade to 4 I am getting LazyInitializationException, which means that 'owners' are not fetched properly. Could you please shed some light on how to solve this problem?
For example when I write this query manually it works completely fine:
List<Car> cars = em.createQuery(
"SELECT DISTINCT c FROM Car c LEFT JOIN FETCH c.owners WHERE c.make = :make ORDER BY c.id ASC")
.setParameter("make", make).getResultList();
I am using spring-boot 2 with querydsl 4.1.4
BTW, query which worked fine in querydsl 3
List<Car> car = new JPAQuery(em)
.from(car)
.leftJoin(car.owners)
.fetch()
.distinct()
.where(car.make.eq(make))
.orderBy(new OrderSpecifier<>(Order.ASC, car.id))
.list(car);

after multiple attempts I have found a solution, here is the code:
new JPAQuery<Car>(em)
.select(car)
.distinct()
.from(car)
.leftJoin(car.owners, owner).fetchJoin()
.where(car.make.eq(make))
.orderBy(new OrderSpecifier<>(Order.ASC, car.id))
.fetch();

I had the same problem and i had to change new JPAQuery(em) to new JPAQuery<Foo>(em)

Related

Spring JPA - How to create a Pageable with a NativeQuery?

I try to do the following inside a Spring Boot application : create a native query and page it so it can returns a page of a given number of elements from a #RestController.
Here's the snippet of my code, where em is the #PersistanceContext EntityManager, and the repository method is the following, knowing that queryString is the native query :
Query searchQuery = em.createNativeQuery(this.queryString, MyEntity.class);
List<MyEntity> resultsList = searchQuery.getResultList();
return new PageImpl<>(resultsList, PageRequest.of(index,size), resultsList.size());
My problem is that the Page returned has a content of the complete query result, not a content of the size of size parameter inside the PageRequest.of.
Has anybody faced the same issue and could give a working example on how to paginate a nativeQuery please ?
Thanks for your help
You are mixing Spring Data JPA (Pageable) with JPA EntityManager. You can't do that. If you are already using a native query then simply put the pagination in the query. You can use what your database supports, for example the standard:
SELECT [a_bunch_of_columns]
FROM dbo.[some_table]
ORDER BY [some_column_or_columns]
OFFSET #PageSize * (#PageNumber - 1) ROWS
FETCH NEXT #PageSize ROWS ONLY;
this is example of using native query with pagination:
#Query("SELECT c FROM Customer As c INNER JOIN Offer as f on f.id=c.specialOffer.id inner join User As u on u.id=f.user.id where u.id=?1 And c.status=?2")
Page<Customer> getAllCustomerToShop(Integer shopId,String status,Pageable pageable)
and then you can call it as:
getAllCustomerToShop(shopId,"status",PageRequest.of(index, PAGE_SIZE));
Modify your code as follows
Query searchQuery = em.createNativeQuery(this.queryString, MyEntity.class)
.setFirstResult(pageable.getPageNumber() * pageable.getPageSize())
.setMaxResults(pageable.getPageSize());

Mapping many-to-many IN statement into JPA (Spring Boot)

I have created two entities in JPA, Listing and ItemType - these exist in a many-to-many relationship (Hibernate auto-generates a junction table). I'm trying to find the best way to create a query which accepts a dynamic list of item type Strings and returns the IDs of all listings which match the specified item types, but I am a recent initiate in JPA.
At present I'm using JpaRepository to create relatively simple queries. I've been trying to do this using CriteriaQuery but some close-but-not-quite answers I've read elsewhere seem to suggest that because this is in Spring, this may not be the best approach and that I should be handling this using the JpaRepository implementation itself. Does that seem reasonable?
I have a query which doesn't feel a million miles away (based on Baeldung's example and my reading on WikiBooks) but for starters I'm getting a Raw Type warning on the Join, not to mention that I'm unsure if this will run and I'm sure there's a better way of going about this.
public List<ListingDTO> getListingsByItemType(List<String> itemTypes) {
List<ListingDTO> listings = new ArrayList<>();
CriteriaQuery<Listing> criteriaQuery = criteriaBuilder.createQuery(Listing.class);
Root<Listing> listing = criteriaQuery.from(Listing.class);
//Here Be Warnings. This should be Join<?,?> but what goes in the diamond?
Join itemtype = listing.join("itemtype", JoinType.LEFT);
In<String> inClause = criteriaBuilder.in(itemtype.get("name"));
for (String itemType : itemTypes) {
inClause.value(itemType);
}
criteriaQuery.select(listing).where(inClause);
TypedQuery<Listing> query = entityManager.createQuery(criteriaQuery);
List<Listing> results = query.getResultList();
for (Listing result : results) {
listings.add(convertListingToDto(result));
}
return listings;
}
I'm trying to understand how best to pass in a dynamic list of names (the field in ItemType) and return a list of unique ids (the PK in Listing) where there is a row which matches in the junction table. Please let me know if I can provide any further information or assistance - I've gotten the sense that JPA and its handling of dynamic queries like this is part of its bread and butter!
The criteria API is useful when you need to dynamically create a query based on various... criteria.
All you need here is a static JPQL query:
select distinct listing from Listing listing
join listing.itemTypes itemType
where itemType.name in :itemTypes
Since you're using Spring-data-jpa, you just need to define a method and annotate it with #Query in your repository interface:
#Query("<the above query>")
List<Listing> findByItemTypes(List<String> itemTypes)

spring data jpa specification join fetch is not working

I am trying to use Spring Data JPA Specificaiton to query data, but I got some problem here.
The Java code is as below:
List<NoticeEntity> studentNoticeEntityList = noticeRepository
.findAll((root, criteriaQuery, criteriaBuilder) -> {
criteriaQuery.distinct(true);
root.fetch(NoticeEntity_.contentEntitySet, JoinType.LEFT);
Predicate restrictions = criteriaBuilder.conjunction();
SetJoin<NoticeEntity, UserNoticeEntity> recipientNoticeJoin = root
.join(NoticeEntity_.recipientNoticeEntitySet, JoinType.INNER);
recipientNoticeJoin.on(criteriaBuilder.equal(
recipientNoticeJoin.get(UserNoticeEntity_.recipientStatus), NoticeRecipientStatus.Unread));
Join<UserNoticeEntity, WeChatUserEntity> recipientUserJoin = recipientNoticeJoin
.join(UserNoticeEntity_.user);
restrictions = criteriaBuilder.and(restrictions,
criteriaBuilder.equal(recipientUserJoin.get(WeChatUserEntity_.id), id));
// recipientNoticeJoin.fetch(UserNoticeEntity_.user, JoinType.INNER);
return restrictions;
});
When I comment the code "recipientNoticeJoin.fetch(UserNoticeEntity_.user, JoinType.INNER);", it is working fine, but when I un-comment this, I will get error:
org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list
So, I am wondering if join fetch is supported by using Specification way, or there is something wrong with my code.
I know there is another way by using #Query("some hql"), but somehow I just prefer to use the Specification way.
Thanks a lot.
The error specifies that you're missing an entity from your select list. Try this:
criteriaQuery.multiselect(root, root.get(NoticeEntity_.recipientNoticeEntitySet);
Also, hibernate may run a count query first to determine the number of results, and this can cause the above error. You can avoid this breaking by checking the return type of the query before adding the fetch.
Eager fetching in a Spring Specification

jpql query gives different result in different platforms

There's something very weird I encountered with while 'playing' with jpql queries which im very new to .
the first one I tried in Spring boot app working with spring repository
#Query("select he.myGroup from HostEntity he where he.host = ?1 order by he.inGroupSince ")
List<String> getHostGrpIdOrderList(String hostName);
which return just one string, the one with the highest inGroupSince filed
the second and very similar query was in http://jpqlquery.com/
select e.name from Employee e where e.department.id = 4 order by e.name
and here it retunrs Lists of employee names ! and not just the first one like the first query .
So why there's a difference ? why does the query in spring boot app returns only one string and not an ordered list ??

List of Users with their single Role in MVC 6 left joined

Using VS 2015, MVC 6 RC1 and EF 7 RC1 I'm trying to get a list of all users with their single role name.
I have tried all suggestions I have come across on StackOverflow but none have worked.
The SQL I'm looking for is:
SELECT [User].[Email], [Role].[Name]
FROM [User]
LEFT JOIN [UserRoles] ON [User].[Id] = [UserRoles].[UserId]
LEFT JOIN[Role] ON [UserRoles].[RoleId] = [Role].[Id]
I have written the below and tested on LinqPad (works fine) and should have worked in my project but comes up with an error:
var q1 = (from user in _context.Users
join ur in _context.UserRoles on user.Id equals ur.UserId into grp1
from fgrp1 in grp1.DefaultIfEmpty()
join r in _context.Roles on fgrp1.RoleId equals r.Id into grp2
from fgrp2 in grp2.DefaultIfEmpty()
select new { UserEmail = user.Email, UserRoleName = fgrp2.Name }).ToList();
And the error message is:
An unhandled exception occurred while processing the request.
InvalidOperationException: Sequence contains no elements
System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
I don't know if it makes any difference but I have created my own Role Entity as:
public class ExtranetRole : IdentityRole<int> { }
and my own User entity as:
public class ExtranetUser : IdentityUser<int> { }
Any help/suggestions much appreciated.
EF7 RC1 have some bugs, related to LEFT joins. Check https://github.com/aspnet/EntityFramework/issues/3629 - it looks very similar to your problem.
I think the best solution until EF release is just read all three tables separately and join them in memory using linq (to objects). Guaranteed to work :)

Resources