简体   繁体   中英

Select all query not working in hibernate

I have a bean class Student who's data I am saving at exam_center table using hibernate.

Here is the StudentOperation class that implements StudentDeclaration. Here in this class I am able to use the insertStudent function to insert data into the table but when I try to see list of all student records using selectAllStudents function, I always get 0 rows as result. I am new to Hibernate.

package DAO;

import Bean.Student;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

/**
 *
 * @author Rishabh
 */
public class StudentOperation implements StudentDeclaration{

    Session ss;
    SessionFactory sf;
    Transaction tr;

    //Here i manually call the class to test the functions.
    public static void main(String s[]){
        System.out.println("jsadhjadsjgadshj");//To test if main is executed
        StudentOperation sp = new StudentOperation();
        sp.selectAllStudents();
    }

    public StudentOperation() {
        sf = HelpingClasses.SessionFact.getSessionFact();
        ss=sf.openSession();
    }


    @Override
    public long insertStudent(Student student) {
            tr = ss.beginTransaction();
            System.err.println("" + student.getEmail() + student.getAddress());
            Long l = (Long) ss.save(student);
            tr.commit();
            if(l>0)
                return 1;
            else 
                return 0;
    }

    @Override
    public long upDate(long id, Student student) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean delete(long id) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Student selectStudent(long id) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List selectAllStudents() {
        String hql = "from Bean.Student";
        Query query  = ss.createQuery(hql);

        System.out.println(query.getQueryString());
        List<Student> li = query.list();

        ListIterator lit = li.listIterator();
        System.out.println(""+li.size());

        //Here i am printing to see the list I have received from the database.
        while (lit.hasNext()) {            
            Student st  = (Student) lit.next();
            System.out.println(st.getAddress()+"--------------");
        }

        if (li.size()!=0) {
            return li;
        } else {
            return null;
        }
    }

    @Override
    public ArrayList searchByName(String name) {
        throw new UnsupportedOperationException("Not supported yet."); 
    }

}

This is what I get in result::

run:
jsadhjadsjgadshj
Jul 26, 2019 7:37:07 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.2.11.Final}
Jul 26, 2019 7:37:07 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Jul 26, 2019 7:37:07 PM org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
Jul 26, 2019 7:37:08 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
Jul 26, 2019 7:37:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
Jul 26, 2019 7:37:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/exam_center]
Jul 26, 2019 7:37:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root}
Jul 26, 2019 7:37:08 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Jul 26, 2019 7:37:08 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
Jul 26, 2019 7:37:08 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Jul 26, 2019 7:37:09 PM org.hibernate.validator.internal.util.Version <clinit>
INFO: HV000001: Hibernate Validator 5.1.2.Final
Jul 26, 2019 7:37:09 PM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@11acdc30'
build session factory-----------------
Jul 26, 2019 7:37:09 PM org.hibernate.hql.internal.QuerySplitter concreteQueries
WARN: HHH000183: no persistent classes found for query class: from Bean.Student
Jul 26, 2019 7:37:09 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService
INFO: HHH000397: Using ASTQueryTranslatorFactory
from Bean.Student
0

Edit

My hibernate configuration file is ::

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!--
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.

Copyright (c) 2008, 2016 Oracle and/or its affiliates. All rights reserved.

Oracle and Java are registered trademarks of Oracle and/or its affiliates.
Other names may be trademarks of their respective owners.

The contents of this file are subject to the terms of either the GNU
General Public License Version 2 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with the
License. You can obtain a copy of the License at
http://www.netbeans.org/cddl-gplv2.html
or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
specific language governing permissions and limitations under the
License.  When distributing the software, include this License Header
Notice in each file and include the License file at
nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
particular file as subject to the "Classpath" exception as provided
by Oracle in the GPL Version 2 section of the License file that
accompanied this code. If applicable, add the following below the
License Header, with the fields enclosed by brackets [] replaced by
your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"

If you wish your version of this file to be governed by only the CDDL
or only the GPL Version 2, indicate your decision by adding
"[Contributor] elects to include this software in this distribution
under the [CDDL or GPL Version 2] license." If you do not indicate a
single choice of license, a recipient has the option to distribute
your version of this file under either the CDDL, the GPL Version 2 or
to extend the choice of license to its licensees as provided above.
However, if you add GPL Version 2 code and therefore, elected the GPL
Version 2 license, then the option applies only if the new code is
made subject to such option by the copyright holder.

Contributor(s):
-->
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/exam_center</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.formate_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">create-drop</property>
    <!--<property name="hbm2ddl.auto">validate</property>-->
    <mapping class="Bean.Student"></mapping>
  </session-factory>
</hibernate-configuration>

the error is clear "no persistent classes found for query class: from Bean.Student" the HQL query should be

select s from Student s

note : try to refactor your code, no one is still using session factory to run jpa queries anymore. but maybe it is a legacy system

您的查询错误,请使用此查询进行更改。

      String hql = "from Student";

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