Hibernate get List from database

前端 未结 6 1171
盖世英雄少女心
盖世英雄少女心 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: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 list = (List) 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 list = (List)sqlQuery.addEntity(Entity.class).list();
    

    That's all. I hope someone will help.

提交回复
热议问题