Hibernate createNativeQuery using IN clause - java

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.

Related

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!

Hibernate query build

Currently i am using the CreateSQLQuery query model to read the data from database using HIbernate. Now, I want to modify my query by using either HQL or Hibernate Criteria. My query looks like as follows.
select concat(d.AREA,' ',d.CITY) as location, a.TRANSFERRED_DATE as ActualTransferDate, concat(c.SCAN_CODE,',',c.SERIAL_NO) as ScanserialCode, c.MODEL_NO as ModelNum, c.ASSET_NAME as AssetName from table_transfer a, table_category b, table_asset c, table_location d where a.ASSET_ID = c.ASSET_ID and b.ASSET_CATEGORY_ID = c.ASSET_CATEGORY_ID and a.TRANSFER_TO_LOCATION=d.LOCATION_ID"
I am not sure how can i can convert this to Hibernate SQL or Criterion based query. Can any one help me?
You can introduce the fields for location and scanserialCode in your entity and mark them as #Formula
e.g.
#Formula("concat(d.AREA,' ',d.CITY)")
private String location;
See an example here or here
Then use join and where in HQL or Hibernate Criteria

Delete data from JPA without using SQL

im familiar with this following way to delete the data (just the data ,not the entity itself)
from the entity
entityManager.getTransaction().begin();
entityManager.createQuery("DELETE FROM " + className)
.executeUpdate();
entityManager.getTransaction().commit();
there is another way to do that like to provide the entityname and then reomve all the data .
You're not using SQL in your code but JPQL, JPA Query Language.
There is no other way to delete all data at once, except by loading all of them and deleting them one by one. It's not even possible with criteria queries since they don't support delete operation yet.
Well.. in this case both NativeSQLQuery and JPQL resolve to the same thing. What you did is JPQL way. The following you could write a nativeSQLQuery
EntityManager em = ...;
Query query = em.createNativeQuery ("SELECT * FROM EMP", Employee.class);

Hibernate Criteria equivalent for IN clause in Subqueries?

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.

Categories

Resources