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 ??
Related
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());
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)
I have a complex query(using multiple joins and subqueries) written in HQL which I have used in a Repository class. Similar to one below -
#Repository
public interface DataRepository extends PagingAndSortingRepository<Data,String> {
public List<Data> findByService(#Param("service")Service service, Pageable page);
#Query("SELECT DISTINCT d from Data d "
+" WHERE (d.working in (SELECT d1 from Data d1 "
+" JOIN d1.working d1w "
+" JOIN d1.service s WITH (s in (:serviceList)))"
+" OR d.cleared IS NOT NULL) AND [..several other CRITERIA]")
public Page<Data> findForServices(#Param("serviceList")Set<Service> serviceList, Pageable page);
....
Now I need to add criteria to it dynamically. These criteria are flexible in number which is holding me from including it into the HQL straightaway. Is it anyhow possible?
Sifting through the internet I have come across solutions for dynamic query. But, I guess they would be working only for cases where I do not have a custom query i.e.- no #Query at the query in the repository.
There was another interesting question I found. But that also suits for a case where you have a single table to query.
I do not want to be switching over to raw SQL queries. How do I solve this?
The mentioned Criteria API with specifications and predicates is a little bit difficult to get used to but it is a good way to handle dynamic conditions.
I don't think it is possible to mix the annotation based query with programmatic query creation.
I am trying to fetch the employee details whose empltype is clerk and whose joining date is the recent one.
For which the query looks like following in SQL Server 2008:
select
*
from
employee jj
inner join
(
select
max(join_date) as jdate,
empltype as emptype
from
employee
where
empltype='clerk'
group by empltype
) mm
on jj.join_date=mm.jdate and jj.empltype=mm.emptype;
I am using SpringData JPA as my persistence layer using QuerylDSL,Specification and Predicate to fetch the data.
I am trying to convert the above query either in QueryDSL or Specification, but unable to hook them properly.
Employee Entity :
int seqid;(sequence id)
String empltype:
Date joindate;
String role;
Predicate method in Specifcation Class :
Predicate toPredicate(Root<employee> root,CriteriaQuery <?> query,CriteriaBuilder cb)
{
Predicate pred=null;
// Returning the rows matching the joining date
pred=cb.equal(root<Emplyoee_>.get("joindate"));
//**//
}
What piece of code should be written in //**// to convert about SQL query to JPA predicate. any other Spring Data JPA impl like #Query,NamedQuery or QueryDSL which returns Page also works for me.
Thanks in advance
I wrote this in notepad and it hasn't been tested but I think you're looking for something like
QEmployee e1 = new QEmployee("e1");
QEmployee e2 = new QEmployee("e2");
PathBuilder<Object[]> eAlias = new PathBuilder<Object[]>(Object[].class, "eAlias");
JPASubQuery subQuery = JPASubQuery().from(e2)
.groupBy(e2.empltype)
.where(e2.empltype.eq('clerk'))
.list(e2.join_date.max().as("jdate"), e2.emptype)
jpaQuery.from(e1)
.innerJoin(subQuery, eAlias)
.on(e1.join_date.eq(eAlias.get("jdate")), e1.emptype.eq(eAlias.get("emptype")))
.list(qEmployee);
//this query can be used to get list of PaymentAttribute for whicch payment details is NOT NULL
#Query("select p.paymentDetailName from paymentattribute p where p.entityId=?1 AND p.entityType=?2 and p.paymentDetailName is not null")
List<String> getNonNullPaymenyDetaisName(String entityId,String entityType);
My paymentattribute table contains some column like entityId, entityType,paymentDetailsName etc. I want to fetch just paymentdetail column as per query stated above . I am getting error. Is there is way in Spring-mvc web applications , via which i can fetch just the column rather than complete tuples. Above code is part of repository.