Entity Manager ORDER BY query with Sort Object - java

I am using the Entity-Manager and want to append the "ORDER BY" query comming from the Sort (org.springframework.data.domain.sort) Object.
The Sort object contains something like "id: DESC".
i can parse the Sort object as a String removing the condition and appending it to my query. the query would looks like this "SELECT p FROM projects ... ORDER BY p.id DESC"
Is there a better way to tackle this problem, any suggestions?
Sorry maybe my description is a bit missleading but i have a REST api and my method gets the Sort object inlcuding the field i need to order by and the direction. I cant easily order it ASC or DESC. its depending on the Sort object i own with the method usage.

Last week, i was checked for the same issue and changed my code as like below: it was worked Fine;sharing the same to you.
StringBuilder strBuilder = "SELECT p FROM projects";
entityManager.createQuery(strBuilder.toString());
Iterator<Order> orderIterator = sort.iterator();
Order order = orderIterator.next();
strBuilder.append(" Order By ").append(order.getProperty()).append(" ")
.append(order.getDirection().name());

Simply use the descending method on you Sort object to get what you need.
query.orderBy(mySort.descending());

Related

Java Hibernate - Query with a list as join

In java code I generate thousands of ids, next I need to get those ids in the postgresql database, so far I have this (used createNativeQuery as pseudocode):
Query q = em.createNativeQuery(
"select * from mytable where id in (:ids)"
).setParameter("ids", listofIds);
I'm afraid about the IN clause, I fear that there might be a huge number of values, is there another better way to perform this?
I think you can scale to quite large lists by doing
select * from mytable where id = any(cast(:ids as bigint[]))
but you have to format the list of ids as a string in Java first, like
ids = "{" + String.join(",", listofIds) + "}";
Still, there will always be some threshold where the list is just too large for Java or Postgresql to handle, so you'll need to break it up into batches if you want to support arbitrarily large lists.

how to map query result to string array in java

select id,name,salary,city,state,country from employee where name like '%a%';
I need to map above query result to String array, position 0 always id, position 1 always name ...... position 5 always country.
Using JPA or MyBatis is there a way we can dynamically map the select query values into fixed position string array ?
I've never personally used JPA, but - after reading through it a bit - believe this should be correct.
TypedQuery<Object[]> query = entityManager.createQuery(
"SELECT id,name,salary,city,state,country FROM employee WHERE name LIKE '%a%'", Object[].class);
List<Object[]> results = query.getResultList();
where (Integer) results.get(index)[0] = id, (String) results.get(index)[1] = name, etc.
You can change Object[] to String[] if you would like an array of Strings.
Why do you want to use String array?
It is better to use an object list instead. It will be easier to get city of an employee using employee.getCity() versus array[3].
It makes for more readable code as well.
To use an object list, you need to create a model for your employee and annotate with #Entity and create a repository for that entity. JPA documentation should help do this easily

jOOQ: returning list with join,groupby and count in single object

Core question: how do you properly fetch information from a query into objects?
Idea
I am creating functions in my DAO, which comes down to the following query:
select A.*, count(*)
from A
left join B on B.aId = A.aId
group by A.*
Im looking for a way to create a jOOQ expression that just gives me a list (or something I can loop over) with objects A (pojo) and Integer.
Concrete case
In my code case: A = Volunteer and B = VolunteerMatch where I store several matches for each volunteer. B has (volunteerId, volunteerMatchId) as primary
key. Thus this query results in both the information from the Volunteer, as well as the number of matches. Clearly this can be done in two seperate queries, but I want to do it as one!
Problem
I cannot find a single object to return in my function. I am trying to get something like List<VolunteerPojo, Integer>. Let me explain this better using examples and why they dont fit for me.
What I tried 1
SelectHavingStep<Record> query = using(configuration())
.select(Volunteer.VOLUNTEER.fields())
.select(Volunteermatch.VOLUNTEERMATCH.VOLUNTEERID.count())
.from(Volunteer.VOLUNTEER)
.leftJoin(Volunteermatch.VOLUNTEERMATCH).on(Volunteermatch.VOLUNTEERMATCH.VOLUNTEERID.eq(Volunteer.VOLUNTEER.VOLUNTEERID))
.groupBy(Volunteer.VOLUNTEER.fields());
Map<VolunteerPojo, List<Integer>> map = query.fetchGroups(
r -> r.into(Volunteer.VOLUNTEER).into(VolunteerPojo.class),
r -> r.into(Volunteermatch.VOLUNTEERMATCH.VOLUNTEERID.count()).into(Integer.class)
);
The problem with this, is that I create a List from the integers. But that is not what I want, I want a single integer (the count will always return one row). Note: I don't want the solution "just create your own map without list", since my gut says there is a solution inside jOOQ. Im here to learn!
What I tried 2
SelectHavingStep<Record> query = using(configuration())
.select(Volunteer.VOLUNTEER.fields())
.select(Volunteermatch.VOLUNTEERMATCH.VOLUNTEERID.count())
.from(Volunteer.VOLUNTEER)
.leftJoin(Volunteermatch.VOLUNTEERMATCH).on(Volunteermatch.VOLUNTEERMATCH.VOLUNTEERID.eq(Volunteer.VOLUNTEER.VOLUNTEERID))
.groupBy(Volunteer.VOLUNTEER.fields());
Result<Record> result = query.fetch();
for (Record r : result) {
VolunteerPojo volunteerPojo = r.into(Volunteer.VOLUNTEER).into(VolunteerPojo.class);
Integer count = r.into(Volunteermatch.VOLUNTEERMATCH.VOLUNTEERID.count()).into(Integer.class);
}
However, I do not want to return the result object in my code. On each place I call this function, I am calling the r.into(...).into(...). During compile time, this won't give an error if it returns an integer or a real pojo. I don't want this to prevent future errors. But at least it doesn't give it in a List I suppose.
Reasoning
Either option is probably fine, but I have the feeling there is something better that I missed in the documentation. Maybe I can adapt (1) to not get a list of integers. Maybe I can change Result<Record> into something like Result<VolunteerPojo, Integer> to indicate what objects really are returned. A solution for each problem would be nice, since I am using jOOQ more and more and this would be a good learning experience!
So close! Don't use ResultQuery.fetchGroups(). Use ResultQuery.fetchMap() instead:
Map<VolunteerPojo, Integer> map =
using(configuration())
.select(VOLUNTEER.fields())
.select(VOLUNTEERMATCH.VOLUNTEERID.count())
.from(VOLUNTEER)
.leftJoin(VOLUNTEERMATCH)
.on(VOLUNTEERMATCH.VOLUNTEERID.eq(VOLUNTEER.VOLUNTEERID))
.groupBy(VOLUNTEER.fields())
.fetchMap(
r -> r.into(VOLUNTEER).into(VolunteerPojo.class),
r -> r.get(VOLUNTEERMATCH.VOLUNTEERID.count())
);

HibernateSearch query

I am new to hibernate Search and i find difficulty in forming Hibernateserach query.
I need to use IN opeartor to the List the String in Hibernate query .
Can anybody help me to sort out this issue.
My current query look like this
String querystring="country:"+profile.getCountry()+" AND religion:"+profile.getReligion()+" AND caste:"+profile.getCaste()+" AND gender:"+profile.getGender()+"AND profession : "+professions+" AND age:["+profile.getFromage()+" TO "+profile.getToage()+"]" ;
here is professions is a list of string.
Regards,
Arun
There is no IN operator in Lucene query language. You will have to expand the string yourself. An alternative for using the query parser would be to use a Lucene BooleanQuery and add the different parts of your query to it, for example a RangeQuery etc. Effectively the QueryParser creates under the hood this lower level queries for you. Have a look at the Lucene API and the different sub classes of org.apache.lucene.search.Query. You still have to expand the collection string yourself though.
Last but not least, you could use the Hibernate Search query DSL. Have a look at the online docs of Hibernate Search if you want to know more - http://docs.jboss.org/hibernate/stable/search/reference/en-US/html_single/#search-query-querydsl
You need to add the following clauses to your query SELECT, FROM, and WHERE. Also the conditions are missing parts. For example here is a valid query. "SELECT e from Employee where e.country = :country and e.religion = :religion"...

How to search strings in java

I currently search the database to get certain results with a pl/sql query like this:
SELECT
*
FROM
citrostats cs
WHERE
(
trim(upper(cs.name)) like trim(upper('%'|| ? ||'%'))
OR
trim(upper(cs.UCODE)) like trim(upper('%'|| ? ||'%'))
)
ORDER BY NAME DESC
I reorganised this, and fetched all rows into Lists of Objects with have the respective columns as String attributes.
What I need is a java code that would search attributes that are String type to give the same set of objects as results like this query has.
Anyone can help?
There is String#contains:
if (name.toUpperCase().contains(uppercasedSearchString))
Since you are doing this in a loop, save work by upper-casing the search string only once before the loop.

Categories