SpringBoot named query: IN-clause not working for multiple values - spring-boot

"In clause" not working on passing multiple values
Repository code
#Query( "select myObject from MyObject myObject where myObject.anyColumn in :values" )
public List<MyObject> findPriDestByCntryAbbr(#Param("values") List<String> values);
Calling from service
List<String> values = Arrays.asList(valuesString.split(","));
List<MyObject> result = myObjectRepository.findByAnyColumns(values);
When i am passing single value it is retrieving correct information from table, But on passing multiple values in List "values" giving empty result

Ideally it should work. You should check the values variable.
The other way you can try is- without writing query.
As per the doc we can create MyObjectRepository interface by extending Repository interface and then have a method to fetch all MyObjects. It goes like:
public interface MyObjectRepository extends Repository<MyObject,**Long**> {
List<MyObject> findBy**AnyColumn**In(Collection<String> values);
}
"AnyColumn" is your column name and second parameter for Repository interface is as per your requirement.

Related

SpringData JPA: Query with collection of entity as parameter

I have a list of entities on which I want to perform an update, I know I could update the table with list of String/Integer.. etc as the parameter with something like
#Query("update tableName i set i.isUpdated = true where i.id in :ids")
void markAsUpdated(#Param("ids") List<Integer> itemIds);
I'm trying to avoid repeated conversion of list of entities to list of Ids for making the query in DB. I know there are deleteAll and deleteInBatch commands which accept parameter as list of entities.
How do I do this in JPA Query, I tried the following but it didn't work yet.
#Modifying(flushAutomatically = true, clearAutomatically = true)
#Query("update tableName i set i.updated = true where i in :items")
void markAsUpdated(#Param("items") List<Item> items)
The query needs ids, it doesn't know how to deal with entities.
You have multiple options:
Just pass ids to the method, the client is responsible for extracting ids.
Pass entities and use SpEL for extracting ids
As suggested in the comments use a default method to offer both APIs and to delegate from one to the other.
As for the question that came up in the comments: You can move the method for extracting the id into a single method by either have relevant entities implement an interface similar to this one:
interface WithId {
Long getId();
}
Or by passing a lambda to the method, doing the conversion for a single entity:
List<ID> extractIds(List<E> entities, Function<E, ID> extractor) {
// ...
}

Passing several query parameters to a GET endpoint in .netcore web api

I have an application where there will be several parameters passed to my endpoint for searching, these parameters are not defined because they are dynamically generated so i cannot map it to a specific model. What would be the best way to map any query parameters into my GET endpoint?
[HttpGet]
public CustomResponse GetResults({something here that will map the parameters?})
{
//perhaps a dictionary? a collection of some sort?
}
Then I need to get all those keys and values and search the database for anything containing that and as i said it could be anything.
So I could pass something like?
/api/Merchandise/GetResults?sku=30021&cupsize=medium&color=red&location=south& {and all the dynamic fields which could be anything}
HttpRequest object has Query property that is an IQueryCollection and holds all passed query parameters.
In other words, in your action method you may do:
[HttpGet]
public CustomResponse GetResults()
{
var queryParams = HttpContext.Request.Query;
// directly get by name
var value1 = queryParams["parameter_name"];
// or queryParams.TryGetValue()
foreach (var parameter in queryParams)
{
string name = parameter.Key;
object value = parameter.Value;
}
}
You could map it to JObject, which is like a Dictionary.
Don't forget:
using Newtonsoft.Json;

A Jpa query annotation to return results as key value pairs

I have a users table and I am trying to use annotated Queries in spring boot to get a result set. I am able to get result set as a list, but that does not have field names. How do I get the result set with field name as key and value pairs?
Current response [[1,"Jay"]] , what I want to do is {"id":1,"Name":"Jay"}
-----Here is my repository class-----
#Repository
public interface UsersauthRepository2 extends JpaRepository<Users2,Long> {
#Query("select id,name,email from Users u where LOWER(email) = LOWER(:email) and LOWER(u.password) = LOWER(:password)")
List<Users2> querybyemail(#Param("email") String email,#Param("password") String password);
}
The request doesn't return fields names.
If you need to get them :
You have them already as method argument
You need to use reflection.
Good luck

how to get one column list in DBFlow

I am using DBflow. I have tried many times to try and make a query as follows:
public class ScoreRepository {
public List<Score> findAllScore() {
return SQLite.select()
.from(Score.class)
.queryList();
}
public List<String> findScore01() {
return SQLite.select()
.from(Score.class)
.queryList();
}
}
In my case findScore01(), this method does not work. I want to make one column String List. I do not want to make an Object List.
queryList will give you list of 'Score' Class. To get custom data,
e.g ( join of two tables, or in your case, just 1 column)
you need to make a class that extends from QueryModel. then use
.queryCustomList(customclass.class);
That will give you
List< customclass > ls;
Check this answer for more details:
Get custom Data from 2 tables
You can use queryCustomList for getting a sub table from an existing table or joining two tables. Like Farhan mentioned above you can create a QueryModel class with your required fields and use it to retrieve the score, but it still be a list of your custom model query class, and not list of strings like you needed.
Only solution I can think of is looping your result list and generate a list of strings like :
List<Score> scoreList = SQLite.select(Score_Table.score01)
.from(Score.class)
.queryList();
List<String> score01List = new ArrayList<>();
foreach(Score score: scoreList) {
score01List.add(score.getScore01());
}

Hibernate find object from database by few params

Can't find right query with few params.
Here is my query from DAO class:
public Notebook findByName(String name, Integer UserId) {
return (Notebook) sessionFactory.getCurrentSession().createQuery("from Notebook where ....");
}
I would like to get by this query object of Notebook by few params: name and user id(foreign key).
And i would like to get only one object, not list of objects even he has only 1 element.
The method createQuery(queryString) returns a Query on which you can set the parameters e.g.
Query query = createQuery("from Notebook where id=:id and title=:title");
query.setParameter("id", id);
query.setParameter("title", title);
query.setMaxResults(1);
query.uniqueResult(); // fetch the object.
If the query returns more then one results be sure to set setMaxResults() or an exception will be thrown.
First
Edit to
public Notebook findByName(String name, Integer UserId) {
return (Notebook) ....createQuery("from Notebook where ....")...uniqueResult;
}
BTW: I am not including the part where you are setting the parameters for your query
If there is no a unique result, uniqueResult throws an exception.
Be sure your query statement is very specific and you are including something like master.pk=child.fk (where pk should fk)
could you update and include the complete query statement?

Resources