简体   繁体   中英

Hibernate get List from database

In the following code I am trying to get a List of Products which contains all the products in the database:

public List<Products> getAllProducts() throws Exception{
    try{
     List<Products> products ;
    org.hibernate.Transaction tx = session.beginTransaction();
    products = session.createSQLQuery("SELECT * FROM Products").list();
    if(products.size() > 0)
    {
        return products;
    }
    return null;  
    }
    catch(Exception e)
    {
        throw e;
    }
}

however this exception is thrown:

[Ljava.lang.Object; cannot be cast to mediatek.Products 
List<Products> list = session.createCriteria(Products.class).list();

这将为您提供数据库中产品表的所有记录

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

Forgot to type cast the query. it is working now.

List<Products> products  = (List<Products>) session.createQuery("from Products").list();

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.

如果你使用 sql 查询,你应该在查询的最后添加这一行以获得你想要的列表:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM