I have a Mongo query org.springframework.data.mongodb.core.query.Query with one criteria and I want to update this criteria by adding the same criteria with different value:
query.addCriteria(Criteria.where("clientName").is("client2"));
But this throws:
Method threw
'org.springframework.data.mongodb.InvalidMongoDbApiUsageException'
exception. Due to limitations of the com.mongodb.BasicDocument, you
can't add a second 'clientName' criteria. Query already contains
'{"clientName": "client1"}'
I've tried to remove the criteria using:
query.getQueryObject().remove("clientName")
But it seems like it returns a copy of the criteria and it didn't remove the criteria. I'm still getting the same exception.
How can I properly remove a criteria in Mongo query?
You can do as follow:
#Autowired
private MongoTemplate mongoTemplate;
public Query queryName(Type1 value1, Type2 value2) {
Query query = new Query(new Criteria().orOperator(Criteria.where("field1").is(value1), Criteria.where("field2").is(value2)));
}
Please note that you can change"orOperator" with "andOperator" based on what you need, otherwise you can use a single criteria.
I think that, instead of deleting a criteria, you should create a new query using for example the function above.
Related
I need to delete some entities with specific field being in an other query with help of CriteriaBuilder & CriteriaDelete. hare is what i have tries so far.
CriteriaDelete<Y> criteriaDelete = criteriaBuilder.createCriteriaDelete(orphan);
Root<Y> deleteRoot = criteriaDelete.from(one_type);
Root<T> queryRoot = criteriaDelete.from(other_type);
criteriaQuery.select(queryRoot.get(key));
entityManager.createQuery(criteriaDelete
.where(deleteRoot.in(entityManager.createQuery(criteriaQuery
.where(queryRoot.get("id").in(givenList))).getResultList())));
Which deleteRoot stands for entity that i want to remove and queryRoot can be any associated entity with in main entity, which we seek for having criteria delete with in expression from that, after executing method that contains the shared snippet, no data will affected.
With respects of properly adding predicates based on aliases and query components, once should explicitly call the executeUpdate method on javax.persistence.Query
entityManager.createQuery(criteriaDelete
.where(deleteRoot.in(entityManager.createQuery(criteriaQuery
.where(queryRoot.get("id").in(givenList))).getResultList())));
Some thing like
entityManager.createQuery(...).executeUpdate();
I have an HQL query that takes msisdn and subServiceId on an Entity Unsubscription.
Below is the code for the same:
Query query = session.createSQLQuery(unsubscriptionInfodemo)
.addEntity(Unsubscription.class)
.setParameter("msisdn", msisdn)
.setParameter("subServiceId", subServiceId);
Now,I need to check in this Unsubscription entity whether subServiceId is the subServiceId I have passed or it should be the subServiceId I have hardCoded.
Can I apply like
public void checkUser(String msisdn,String subServiceID){
Query query = session.createSQLQuery(unsubscriptionInfodemo)
.addEntity(Unsubscription.class)
.setParameter("msisdn", msisdn)
.setParameter("subServiceId", subServiceId)
.setParameter("subServiceId", "XYZ");
}
HQL query:
unsubscriptionInfodemo=select * from unsubscription s where s.msisdn=:msisdn and s.subservice_id=:subServiceId
Can anyone guide me how to proceed?
How to apply OR Condition in HQL?
use OR on your query:
select * from unsubscription s where s.msisdn=:msisdn and s.subservice_id=:subServiceId OR
s.subservice_id=:subServiceId2
and name parameters shouldn't be the same:
.setParameter("msisdn", msisdn)
.setParameter("subServiceId", subServiceId)
.setParameter("subServiceId2", "XYZ"); // Make this subServiceId2
The dynamic functionality you want to implement cannot be done with hql without changing the hql string.
I would consider using the criteria api which provides a dynamic functionality.
The easiest way is to either create the hql string based on the value (if subServiceId is existent or not) or use the criteria api, thus you will just have to add one extra equals filter in case of subServiceId presence.
The question should be changed on how to add dynamic conditions to hql based on variable presence.
Also check this answer
EDIT: Solutions to this problem are provided in the second and fourth answer regarding this question setMaxResults for Spring-Data-JPA annotation?
Goal: Fetch the largest/smallest element by property z using a Spring Data JPA repository and the Spring Query annotation.
What I have so far
#Query("SELECT xelement FROM x xelement ORDER BY xelement.z")
public List<X> findFirstElement();
Problem: This query fetches all elements (which is not really effective). If I would use the EntityManager direcly, I could set the number of results using
entityManager.setMaxResults(1)
to only get the first element.
Question: How do I specify the maximum number of results using the #Query annotation?
Idea: Is using a PageRequest of size 0 the way to go?
Constraints: I am aware of the "FindFirstBy...." query feature but I want/have to use the #Query annotation.
You can use the limit property of sql just by adding nativeQuery to #Query annotation. However, there is another and a better way of doing this. Pageable class in your repository method will solve your problem without touching your #Query annotation:
#Query(value = "SELECT xelement FROM x xelement ORDER BY xelement.z")
List<X> findFirstElement(Pageable limit);
To set the limit and offset, use should call this repository method as follows:
List<X> xValues = xRepository.findFirstElement(new PageRequest(0, 1));
Here 1 corresponds to the limit which you want.
UPDATE (SPRING DATA 2.0)
Use PageRequest.of(0, 1) instead of new PageRequest(0, 1)
The closest JPA query syntax I can think for your use case is findFirstByZIsNotNullOrderByZAsc. This should eliminate the need to write custom native query.
Try to do this:
#Query(value = "SELECT xelement FROM x xelement ORDER BY xelement.z LIMIT 1",
nativeQuery = true)
I would like to translate a query like this one:
FROM Entity_1 obj
WHERE obj IN (FROM Entity2) OR
obj IN (FROM Entity3)
To hibernate Criteria form, and the official documentation of Hibernate is not enough because it doesn't say how to apply the IN statement.
Any hint?
The criteria API does not have a provision to add another query as a restriction.. i think what #Niroshan Abayakoon was trying to say is that you need to execute the queries for the IN clause seperatly & add the result to the Restrictions.in() condition.
List<?> entity2Data=//get data from either a query or criteria
List<?> entity3Data=//get data from either a query or criteria
Criteria c = // obtain criteria from session
// basically creates an OR condition chain
Disjunction orConditions = Restrctions.disjunction();
orConditions.add(Restrictions.in("obj", entity2Data));
orConditions.add(Restrictions.in("obj", entity3Data));
c.add(orConditions);
this would get hibernate to consider the list within the IN clause.
Its always better to fallback to HQL in situations like this.
Using Java, Hibernate.
I have a query
String pixIds = "1,2,3";
String query = "SELECT * FROM comment WHERE PIX_ID IN (:pixIds)";
q.setParameter("pixIds", pixIds);
List<Object[]> results = q.getResultList();
I'm not able to bind this parameter to pixIds using the code above. What is the right way to do this?
Note : the query I have here is a simplified version of my actual query.
The following method works
public Query setParameterList(String name, Collection vals) throws HibernateException
Hibernate doesn't support binding collection to IN (...) in SQL queries.
You need to work the same way as with plain JDBC: given a collection, dynamically generate a query with appropriate number of ?s in IN clause, and then bind elements of that collection to ?s.