【问题标题】:Select all query not working in hibernate选择所有在休眠状态下不起作用的查询
【发布时间】:2019-12-04 22:26:02
【问题描述】:

我有一个 bean 类 Student,我使用 hibernate 将数据保存在exam_center 表中。

这是实现 StudentDeclaration 的 StudentOperation 类。在这个类中,我可以使用 insertStudent 函数将数据插入表中,但是当我尝试使用 selectAllStudents 函数查看所有学生记录的列表时,我总是得到 0 行结果。我是 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."); 
    }

}

这是我得到的结果::

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

编辑

我的休眠配置文件是::

<?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>

【问题讨论】:

    标签: java mysql hibernate jakarta-ee


    【解决方案1】:

    错误很明显“没有为查询类找到持久类:来自 Bean.Student” HQL 查询应该是

    select s from Student s
    

    注意:尝试重构您的代码,没有人仍在使用会话工厂来运行 jpa 查询。但也许它是一个遗留系统

    【讨论】:

    • 你甚至可以只用FROM Student
    • @ali ahmed 当我尝试您的解决方案时,我收到异常说学生未映射。
    • 你能不能把Student这个类,还有为什么你把包命名为Bean?
    • @aliahmed 我还有很多其他的 Bean 类,我已经放在那里了
    【解决方案2】:

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

          String hql = "from Student";
    

    【讨论】:

    • 当我这样做时,它会抛出一个异常,说没有映射此类。
    • 你能试试这个。 ss.get(Student.class) 获取所有学生列表
    猜你喜欢
    • 1970-01-01
    • 2012-12-30
    • 2011-07-20
    • 2019-03-28
    • 1970-01-01
    • 2013-08-03
    • 2011-04-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多