Hibernate Criteria equivalent for IN clause in Subqueries? - java

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.

Related

Detaching by JPA CriteriaDelete with in-expression having subquery seems not executing properly

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();

How to remove a criteria in Spring Mongo Query

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.

Difference between hibernate query api and criteria api [duplicate]

Can anyone please tell me the difference between Hibernate's:
createCriteria
createQuery
createSQLQuery
Can anyone tell me what data these three functions return, c.q. direct me to a proper and simple link to study these Hibernate functions?
To create query in the Hibernate ORM framework, there is three different types. The following are the three ways to create query instance:
session.createQuery()
session.createSQLQuery()
session.createCriteria()
Look into the details of each category in detail.
Session.createQuery()
The method createQuery() creates Query object using the HQL syntax. For example:
Query query = session.createQuery("from Student s where s.name like 'k%'");
Session.createSQLQuery()
The method createSQLQuery() creates Query object using the native SQL syntax. For example:
Query query = session.createSQLQuery("Select * from Student");
Session.createCriteria()
The method createCriteria() creates Criteria object for setting the query parameters. This is more useful feature for those who don't want to write the query in hand. You can specify any type of complicated syntax using the Criteria API.
Criteria criteria = session.createCriteria(Student.class);
1. session.createQuery()-> Can create query using HQL and can perform CRUD Operations
Example:
Query query = session.createQuery("from Student");
List list=quey.list();
Query query = session.createQuery("update Student where studentid=9");
int result=query.executeUpdate();
Query query = session.createQuery("delete Student where studentid="+ studentId);
int result=query.executeUpdate();
Query query = session.createQuery("insert into Student where studentid="+ studentId);
int result=query.executeUpdate();
session.createSQLQuery()-> Can create query using SQL and can perform CRUD Operations
session.createCriteria()->Can create query using Criteria API and can perform only Read Operations
------------------------
PERSON
------------------------
**DB_Column**| **POJO**
PERSON_ID | personID
------------------------
createQuery()
you are using pojo fields. Using HQL syntax.
Query query = session.createQuery("from Person s where s.personID like 'A%'");
// returns:
List<Person> persons = query.list();
createSQLQuery()
You are using Native|DB fields.
After googling some site, Came to know this will also clear the cache as hibernate don't know the what you have executed.
Query query = session.createSQLQuery("select s.* from Person s where s.person_ID like 'A%'");
// returns:
List<Object[]> persons = query.list();.
createCriteria()
Create sql query using Criteria object for setting the query
parameters.
Useful when switching DB.
Read only query
Criteria criteria = session.createCriteria(Person.class);
criteria.add(Restrictions.like("personId", "A%"));
List<Person> persons = criteria .list();
createSQLQuery -- is for native sql querying which is selected by you with jdbc driver cfg or something else.
createQuery -- is for hibernate querying which provides you independent querying which makes you run that on many databases using API and more other advantages.
createCriteria -- is better to use for simple querying on db because of it's simplicity.
I hope this helps you!

How to apply OR Condition in HQL?

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

Hibernate createNativeQuery using IN clause

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.

Categories

Resources