首页 > 解决方案 > 在 OneToMany 单向 Realtion 之后从数据库中检索数据

问题描述

所以我得到了这个项目,我在数据库中存储了一个“Categorie”类,该类与“SousCategorie”类的单调关系工作正常,它创建了一个名为“categorie_sous_categories”的表

当我厌倦了从categorie_sous_categories表中检索数据时,发生了一个错误,即这个类被映射到哪个休眠创建了表但我没有在我的程序中声明该类我的程序结构: 在此处输入图像描述 异常日志:

Exception in thread "main" java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: Categorie_sous_categories is not mapped [select categorie_matricule from categorie_sous_categories]

我尝试运行的代码:

SessionFactory sessionFactory = new Configuration().
                configure().buildSessionFactory();


        Session session = sessionFactory.openSession();
        session.beginTransaction();

        List<String> categorieList = session.createQuery("select categorie_matricule from categorie_sous_categories").list();
        for (String produit:categorieList){
            System.out.println(produit);
        }

        session.getTransaction().commit();
        session.close();

我尝试从中检索数据的表: 在此处输入图像描述

我的 hibernate.cfg.xml 文件:

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
    <session-factory>

        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/DevIT</property> <!-- BD Mane -->
        <property name="connection.driver_class">org.postgresql.Driver</property> <!-- DB Driver -->
        <property name="connection.username">postgres</property> <!-- DB User -->
        <property name="connection.password">test123</property> <!-- DB Password -->

        <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property> <!-- DB Dialect -->
        <property name="hbm2ddl.auto">update</property> <!-- create / create-drop / update -->

        <property name="show_sql">true</property> <!-- Show SQL in console -->
        <property name="format_sql">true</property> <!-- Show SQL formatted -->
        <property name="hibernate.current_session_context_class">thread</property>
        <mapping class="CoreApp.Categorie"/>
        <mapping class="CoreApp.SousCategorie"/>
        <mapping class="CoreApp.Produit"/>
    </session-factory>
</hibernate-configuration>

标签: javadatabasehibernate

解决方案


try select categorie_matricule from Categorie,它将返回预期的结果。此外,异常是不言自明的,表categorie_sous_categories没有与任何 Entity/Class 映射,它是一个映射表。并且不应该直接获取它,您想在此表上运行的任何查询都可以更改 -Categorie and SousCategorie使用原始类的位置。


推荐阅读