Hibernate get List from database

前端 未结 6 1168
盖世英雄少女心
盖世英雄少女心 2021-02-07 22:31

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          


        
相关标签:
6条回答
  • 2021-02-07 22:38

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

    List<Products> products  = (List<Products>) session.createQuery("from Products").list();
    
    0 讨论(0)
  • 2021-02-07 22:41
    List<Products> list = session.createCriteria(Products.class).list();
    

    This will give you all the records of products table from database

    0 讨论(0)
  • 2021-02-07 22:43

    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.

    0 讨论(0)
  • 2021-02-07 22:47

    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();
    
    0 讨论(0)
  • 2021-02-07 22:49

    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();
    
    0 讨论(0)
  • 2021-02-07 22:52

    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();
    
    0 讨论(0)
提交回复
热议问题