In the following code I am trying to get a List of Products which contains all the products in the database:
public List getAllProducts() throws
Forgot to type cast the query. it is working now.
List<Products> products = (List<Products>) session.createQuery("from Products").list();
List<Products> list = session.createCriteria(Products.class).list();
This will give you all the records of products table from database
For example you have code:
Session session = getSessionFactory().openSession();
Transaction transaction = null;
try {
SQLQuery sqlQuery = session.createSQLQuery("SELECT * FROM schema.yourtable WHERE param = :param");
sqlQuery.setString("param", "someParam");
And if your next step will be:
List list = sqlQuery.list();
You will receive list with Rows. You can see your Entity.class parameters in debug, but cat cast to List with your Entities:
List<Entity> list = (List<Entity>) sqlQuery.list();
In this point will be ClassCastException!
And if you need received List with your Entities you must add entity type to sql query:
List<Entity> list = (List<Entity>)sqlQuery.addEntity(Entity.class).list();
That's all. I hope someone will help.
if you using sql query, you should add this line at the last of the query to get the list you want:
.setResultTransformer(Transformers.aliasToBean(testDTO.class)).list();
In Hibernate 5 the session.createCriteria
methods are deprecated.
You will need to use a CriteriaBuilder and query from there to get a generic list of Products instead of just List
.
Imports
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
Code
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Products> criteria = builder.createQuery(Products.class);
criteria.from(Products.class);
List<Products> products = session.createQuery(criteria).getResultList();
Your answer not only adds a cast, but switches from SQL to HQL. Since your 2nd query is in HQL, Hibernate is able to use mapping information to know what class to return. This is the preferred way to do things in Hibernate, but if you had to use SQL for some reason you could achieve the same thing with:
(List<Products>)session.createSQLQuery("SELECT * FROM Products").addEntity(Products.class).list();