Difference between hibernate query api and criteria api [duplicate] - java

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!

Related

Can #Query annotation in Spring Data JPA take in a list of enums?

I've been trying to figure out how to take an input of a list of enums for my sql query. This is what it looks like:
#Query(value = "Select * from employees where city in :cities", nativeQuery = true)
List<Employee> findByCities(#Param("cities") List<City> cities);
I understand that for simple queries we can rely on the JPA Criteria API but I want to know if I can actually do it this way instead. Because if so, i can create more complicated queries (such as joins with another table) if I could have this flexibility of specifying the list.
Yes spring-data-jpa's #Query can take a list of enums.
This is my repository method
#Query("Select u from User u where u.userType in :types")
List<User> findByType(#Param("types") List<UserType> types);
This is my repository call
userRepository.findByType(Arrays.asList(AppConstant.UserType.PRINCIPLE)))
And this is the query logs
SELECT user0_.id AS id1_12_,
user0_.date_created AS date_created2_12_,
...
...
FROM users user0_
WHERE user0_.user_type IN ( ? )
Hope this helps.
PS: I tested this in my local machine with positive results.
Update 1
The same doesn't work with nativeQuery=true. I tested it on my local system and it doesn't seem to be working with native queries. However with JPQL it works fine as mentioned in the above answer.
May be this answer will help.

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

Hibernate inject Criterion into Query

I have a code with Hibernate restrictions like:
Criterion budgetTypeRestriction;
budgetTypeRestriction = Restrictions.between("code", "01", "03");
And how I can inject Criterion into Query?:
Session session = sessionFactory.getCurrentSession();
Query query = session.createQuery("from Regions");
It is easy for me collect Criterion logic, and then pass it to DAO, which is implemented throw Query and parameter binding.
In Query (HQL) you don't use Criterion.
Instead you use HQL expressions in where clause which are similar to SQL:
Query query =
session.createQuery("from Regions r where r.code between '01 and '03'");
I hope you expect the below
List<Regions> regionsList=sessionfactory.getCurrentSession().createCriteria(Regions.class)
.add(Restrictions.between("code", "01", "03")).list();
You probably want to use the Criteria API instead of a query. You can add sql restrictions to a criteria with Restrictions.sqlRestriction() if you need that.

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 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