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
Related
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!
I have my service up and running but there's still a few things i can't figure out.
I have a query that is similar to the following
#Query("SELECT t FROM Tablename t")
Then hibernate will generate the following query
Hibernate: select tname.column1 as a, tname.column2 as b, tname.column3 as c, tname.column4 as d from tablename tname
The problem is that Tablename is case sensitive when i query against a mysql database. Is there a way in hibernate to execute the query exactly the way it is spelled out in the annotation? Also, is it possible to stop hibernate from breaking camelcased columns into two works. For example if i had a column named columnOne hibernate will want to generate a column with the name column_one.
I know this more than likely has something to do with hibernate's naming strategy but i haven't been able to find a solution.
Try adding the following in your application.properties file.
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
Documentation about naming strategies are here
Here is what I am trying to do:
1. Send an HQL to populate "User" Hibernate object.
2. Send a native SQL to retrieve a smaller dataset from a very large data column from "User" table.
3. Combine the mapped Hibernate object with the column result from step 2.
I read that ResultTransformer can be used to map the resultset from 2 to a Hibernate entity, which in my case the "User" entity. Is there a way to insert the results of the ResultTransformer mapping to my original User entity?
Here's some example: 1. HQL - From User. We use Hibernate mapping file for User and using Bytecode Enhancement, we set "xmlStringColumn lazy=true". String hql = "FROM User";
List users = session.createQuery(hql).list(); 2. we send a query
List resultXML = s.createSQLQuery(
"XML SQL to get specific data")
.setResultTransformer( Transformers.aliasToBean(User.class))
.list();
User dto =(User) resultWithAliasedBean.get(0); //Will need code to combine the User dto from the SQL to the original
ResultTransformer bundles one to many relationship objects into single object.
For example,
Class A{
Set b=new Hashset();
}
So if you start query from class A and add join on B it will end up in creating multipe objects of A.
ResultTransformer bundles data into single A object.
Can you please post code so we can understand what you are tyring to acheive!!!
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);
I have this class mapped
#Entity
#Table(name = "USERS")
public class User {
private long id;
private String userName;
}
and I make a query:
Query query = session.createQuery("select id, userName, count(userName) from User order by count(userName) desc");
return query.list();
How can I access the values returned by the query?
I mean, how should I treat the query.list()? As a User or what?
To strictly answer your question, queries that specify a property of a class in the select clause (and optionally call aggregate functions) return "scalar" results i.e. a Object[] (or a List<Object[]>). See 10.4.1.3. Scalar results.
But your current query doesn't work. You'll need something like this:
select u.userName, count(u.userName)
from User2633514 u
group by u.userName
order by count(u.userName) desc
I'm not sure how Hibernate handles aggregates and counts, but I'm not sure if your query is going to work at all. You're trying to select a aggregate (i.e. the "count(userName)"), but you don't have a "group by" clause for userName.
If the query does in fact work, and Hibernate can figure out what to do with it, the results you get back will most likely be a raw Object[], because Hibernate will not be able to map your "count(userName)" data into any field on your mapped objects.
Overall, when you get into using aggregates in queries, Hibernate can get a little more tricky, since you're no longer mapping tables/columns directly into classes/fields. It might be a good idea to read up more on how to do aggregates in Hibernate, from their documentation.