How can I write a custom query with spring in mongo? - spring

I'm trying to make a query and fetch data over mongodb with Spring. But I don't know mongo and spring very well. I have these fields in my table. How can I write a custom query with this query in SQL? I mean give the qp value of the record whose id is this. How can I write this please help..
SELECT qp
FROM tableName
WHERE id = request.getId();
my custom query method is it true?
public Object findQueryParams(ProcessInfo processInfo ){
Query query = Query.query(Criteria.where("id").is(processInfo .getId()).is(processInfo .getQueryParams()));
return query;
}

Related

Stream MongoDB Result of FindAll documents

I want to write a mongo query to fetch All Documents in a collection and project just 2 fields and no criteria.
I want to use streams here and iterate over the list of documents to process them.
How can I write this in Java Spring Mongo?
I have something like this:
public CloseableIterator<Employees> streamAllEmployees() {
Query query = new Query();
query.fields().include("_id.name","_id.dept");
query.addCriteria(Criteria.where("_id.dept").is(1));
return mongoOperations.stream(query, Employee.class);
}
but how can I change this to not have any QueryCriteria?

Spring boot Reactive Mongo Query Interceptor

Is there anyway to intercept the query before executing it ?
for example
I have a userId header in the request and a document (let say book), with the userId stored within its attributes and persisted in the database
is there anyway to inject the userId criteria in all queries in a specific repository ( in this case BookRepository) so that I have a default query where
userId : {userId}
, or I just have to add the criteria in every function ?

Problem with MongoDB #Query annotation/Query

I got problems with #Query annotation or Query query = new Query() - I can't include/exclude some fields.
I find code samples like:
#Query(value = "{'id': ?0}",fields = "{'id':1}")
User findUserById(String id);
Result should be user with only one field -> id but its showing other fields to..
So I found other samples like:
Query query = new Query();
query.fields().include("id");
query.addCriteria(Criteria.where("id").is(id));
User one = mongoTemplate.findOne(query, User.class);
Same result there..
Any ideas?
Integer findUserById(String id);
Use the DataType of Id [like Integer] to get only id.
Change datatype of according the requirement/usecase

How to Return all instances of the type with the given ID in JPA SpringBoot?

I'm trying to return (or fetch) all the records from the database based on an ID provided by me. I'm using JPA and i'm aware of findAll() method but it returns all the records without any criteria, I created a custom query and it is only returning a unique value from the table but i want to return all records based on a criteria.
For example, findAllByUserID(String UserID) method should return all the records based on that UserID not just one.
I'd appreciate any help or suggestion.
Thanks
Have a look at the doc. There you will find the keywords you can use to declare methods in repository interfaces that will generate the according queries:
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods
In your case: If userID is an attribute of your entity you can add a method
List<YourEntity> findByfindAllByUserID(String userId)
to your repository interface.
First, make sure that you're not using any aggregate function in your select query such as DISTINCT()
Then make sure that the the method which is implementing that query is returning a List of you're desired result.
here's how it should look :
#Query("select t from table t where t.code = ?1")
List<Result> findAllByUserID(String UserID);

How to get count of updated records in spring data jpa?

I am using spring data jpa with hibernate as jpa persistence provider.
I am using native queries in my application. There are some update queries and I would like to get the actual number of records updated when the update query gets executed. Is there a way in spring data jpa to do this?
I am currently following the below approach;
#Modifying
#Query(value="update table x set x_provision = ?1 where x_id = ?2", nativeQuery=true)
int updateProvision(Integer provision, Integer id);
#Transactional is added on service layer.
The problem here is that when the table gets updated I get the count as 1. But there are some cases where no rows are updated. In this case also I get the count as 1. But I would like to receive the actual number of records updated which sometimes is 0.
Can someone let me know if I am doing something wrong here?
If you take a look at ModifyingExecutor, which is used to execute this query
#Override
protected Object doExecute(AbstractJpaQuery query, Object[] values) {
int result = query.createQuery(values).executeUpdate();
if (em != null) {
em.clear();
}
return result;
}
Then you see, it only delegates to native JPA infrastructure, to return number of updated elements.
So, this might have to do with used database or ORM framework configuration, other than that, the query you wrote should return correct result.

Resources