Java org.hibernate.hql.internal.ast.QuerySyntaxException:表未映射

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23018836/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:03:57  来源:igfitidea点击:

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

javahibernatederbyglassfish-4

提问by Vlad Dobrydin

I have example web application Hibernate 4.3.5 + Derby database 10.10.1.1+ Glassfish4.0 with IDE NetBeans 8.0Beta.

我有示例 Web 应用程序 Hibernate 4.3.5 + Derby 数据库 10.10.1.1+ Glassfish4.0 和 IDE NetBeans 8.0Beta。

I have the next exception:

我有下一个例外:

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:189)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:109)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:95)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:331)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3633)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3522)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
... 72 more 

Form from index.xhtml

来自 index.xhtml 的表单

<h:panelGrid id="panel1" columns="2" border="1"
                 cellpadding="5" cellspacing="1">
        <f:facet name="header">
            <h:outputText value="Add Customer Information"/>
        </f:facet>
        <h:outputLabel value="First Name:"/>
        <h:inputText value="#{customer.firstName}" id="fn"/>
        <h:outputLabel value="Last Name:"/>
        <h:inputText value="#{customer.lastName}" id="ln"/>
        <h:outputLabel value="Email:"/>
        <h:inputText value="#{customer.email}" id="eml"/>
        <h:outputLabel value="Date of Birth:"/>
        <h:inputText value="#{customer.sd}" id="s"/>
        <f:facet name="footer">
            <h:outputLabel value="#{customer.msg}" id="msg" styleClass="msg"/>
            <h:commandButton value="Save" action="#{customer.saveCustomer}">
            </h:commandButton>
        </f:facet>
    </h:panelGrid> 

Customer.java

客户.java

    package com.javaknowledge.entity;

    import com.javaknowledge.dao.CustomerDao;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.List;
    import javax.faces.bean.ManagedBean;
    import javax.faces.bean.SessionScoped;
    import javax.persistence.*;    

    @ManagedBean
    @SessionScoped

    public class Customer implements java.io.Serializable {

    private Integer custId;
    private String firstName;
    private String lastName;
    private String email;
    private Date dob;
    private String sd, msg, selectedname;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");


    public Customer() {
    }

    public Customer(String firstName, String lastName, String email, Date dob) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.dob = dob;
    }

    public String getSd() {
        return sd;
    }

    public void setSd(String sd) {
        this.sd = sd;
    }

    public Integer getCustId() {
        return this.custId;
    }

    public void setCustId(Integer custId) {
        this.custId = custId;
    }

    public String getFirstName() {
        return this.firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return this.lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    @Column(name = "EMAIL")
    public String getEmail() {
        return this.email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Column(name = "DOB")
    public Date getDob() {
        return this.dob;
    }

    public void setDob(Date dob) {
        this.dob = dob;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public String getSelectedname() {
        return selectedname;
    }

    public void setSelectedname(String selectedname) {
        this.selectedname = selectedname;
    }

    public void saveCustomer() {
        try {
            Date d = sdf.parse(sd);
            System.out.println(d);
            this.dob = d;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        CustomerDao dao = new CustomerDao();
        dao.addCustomer(this);
        this.msg = "Member Info Saved Successfull!";
        clearAll();
    }
    public void updateCustomer() {
        try {
            Date d = sdf.parse(sd);
            System.out.println(d);
            this.dob = d;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        CustomerDao dao = new CustomerDao();
        dao.updateCustomer(this);
        this.msg = "Member Info Update Successfull!";
        clearAll();
    }
    public void deleteCustomer() {
        CustomerDao dao = new CustomerDao();
        dao.deleteCustomer(custId);
        this.msg = "Member Info Delete Successfull!";
        clearAll();
    }

    public List<Customer> getAllCustomers() {
        List<Customer> users = new ArrayList<Customer>();
        CustomerDao dao = new CustomerDao();
        users = dao.getAllCustomers();
        return users;
    }

    public void fullInfo() {
        CustomerDao dao = new CustomerDao();
        List<Customer> lc = dao.getCustomerById(selectedname);
        System.out.println(lc.get(0).firstName);
        this.custId = lc.get(0).custId;
        this.firstName = lc.get(0).firstName;
        this.lastName = lc.get(0).lastName;
        this.email = lc.get(0).email;
        this.dob = lc.get(0).dob;
        this.sd = sdf.format(dob);
    }

    private void clearAll() {
        this.firstName = "";
        this.lastName = "";
        this.sd = "";
        this.email = "";
        this.custId=0;
    }

   }

hibernate.cfg.xml

休眠文件.cfg.xml

<?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">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
    <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
    <property name="hibernate.connection.url">jdbc:derby://localhost:1527/derbyDB</property>
    <property name="hibernate.connection.username">user1</property>
    <property name="hibernate.connection.password">user1</property>
    <property name="hibernate.hbm2ddl.auto">create</property>

    <property name="c3p0.min_size">1</property>
    <property name="c3p0.max_size">5</property>
    <property name="c3p0.timeout">300</property>
    <property name="c3p0.max_statements">50</property>
    <property name="c3p0.idle_test_period">300</property>

    <mapping class="com.javaknowledge.entity.Customer" resource="com/javaknowledge/entity/Customer.hbm.xml"/>
  </session-factory>
</hibernate-configuration>

Customer.hbm.xml

客户.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="com.javaknowledge.entity.Customer" table="CUSTOMERV" schema="APP">
        <id name="custId" type="java.lang.Integer">
            <column name="cust_id" />
            <generator class="increment" />
        </id>
        <property name="firstName" type="string">
            <column name="first_name" length="45" not-null="true" />
        </property>
        <property name="lastName" type="string">
            <column name="last_name" length="45" not-null="true" />
        </property>
        <property name="email" type="string">
            <column name="email" length="45" not-null="true" />
        </property>
        <property name="dob" type="date">
            <column name="dob" length="10" not-null="true" />
        </property>
   </class>
</hibernate-mapping>

采纳答案by Vlad Dobrydin

Finally I found a mistake! Hope this is useful to someone. When doing a request to the database(in my case it Apache Derby), name of base need write the first letter upper case other in lower case.

最后我发现了一个错误!希望这对某人有用。在向数据库(在我的情况下是 Apache Derby)发出请求时,base 的名称需要将第一个字母大写,其他小写。

This is wrong query:

这是错误的查询:

session.createQuery("select first_name from CUSTOMERV").

This is valid query

这是有效的查询

session.createQuery("select first_name from Customerv"). 

And class entity must be same name as database, but I'm not sure.

并且类实体必须与数据库同名,但我不确定。

回答by Vlad Dobrydin

Problem partially was solved. Besides creating jdbc/resource(DB Derby) had to create JDBC Connection Pool for db resource in Glassfish admin console, and check it on pinging. Now all CRUD operation work just fine. I check, object Customer in database adding properly, update and delete too. But in Glassfish output log have same exception:

问题部分解决。除了创建 jdbc/resource(DB Derby) 之外,还必须在 Glassfish 管理控制台中为 db 资源创建 JDBC 连接池,并在 ping 时检查它。现在所有 CRUD 操作都可以正常工作。我检查,正确添加数据库中的对象客户,更新和删除。但是在 Glassfish 输出日志中也有同样的异常:

SEVERE:   org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped [select concat(first_name, ' ', last_name) as name from CUSTOMERV]
    at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:96)
    at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120)
    at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:234)
    .......

Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped
    at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:189)
    at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:109)

回答by connectoram

May be this will make it more clear, and of course makes sense too.

可能这会让它更清楚,当然也有意义。

@Entity
@Table(name = "users")

/**
 * 
 * @author Ram Srinvasan
 * Use class name in NamedQuery
 * Use table name in NamedNativeQuery
 */
@NamedQueries({ @NamedQuery(name = "findUserByName", query = "from User u where u.name= :name") })

@NamedNativeQueries({ @NamedNativeQuery(name = "findUserByNameNativeSQL", query = "select * from users u where u.name= :name", resultClass = User.class) })
public class User implements Principal {
...
}

回答by Siva kumar

There is one more chance to get this exception even we used class name i.e., if we have two classes with same name in different packages. we'll get this problem.

即使我们使用类名,如果我们在不同的包中有两个同名的类,也有更多的机会得到这个异常。我们会遇到这个问题。

I think hibernate may get ambiguity and throws this exception, so the solution is to use complete qualified name(like com.test.Customerv)

我认为 hibernate 可能会产生歧义并抛出此异常,因此解决方案是使用完整的限定名称(如com.test.Customerv

I added this answer that will help in scenario as I mentioned. I got the same scenario got stuck for some time.

我添加了这个答案,这将有助于我提到的场景。我遇到了同样的场景卡住了一段时间。

回答by Barani r

hibernate.cfg.xml file should have the mapping for the tables like below. Check if it is missing in your file.

hibernate.cfg.xml 文件应该具有如下表的映射。检查它是否在您的文件中丢失。

......
<hibernate-configuration>
......
......
  <session-factory>
......
<mapping class="com.test.bean.dbBean.testTableHibernate"/>
......
 </session-factory>

</hibernate-configuration>
.....

回答by Sanjeev Kumar

in HQLquery, Don't write the Table name, write your Entity class namein your query like

HQL查询中,不要写表名,在查询中写下你的实体类名,如

String s = "from Entity_class name";
query qry = session.createUqery(s);

回答by Majid

Other persons that are using mapping classes for Hibernate, make sure that have addressed correctly to modelpackage in sessionFactorybean declaration in the following part:

其他使用 Hibernate 映射类的人,请确保在以下部分正确处理bean 声明中的模型sessionFactory

<property name="packagesToScan" value="com.mblog.model"></property>

回答by Pipo

None of the other solution worked for me.

其他解决方案都不适合我。

Even if I don't think its the best practice, I Had to add it into the codelike this

即使我认为这不是最佳实践,我也必须像这样将其添加到代码中

configuration.addAnnotatedClass(com.myOrg.entities.Person.class);

configuration.addAnnotatedClass(com.myOrg.entities.Person.class);

here

这里

public static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();

    configuration.addAnnotatedClass(com.myOrg.entities.Person.class);

    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
    return sessionFactory;
}

回答by mannedear

If you by any chance using java for configuration, you may need to check the below beandeclaration if you have package level changes. Eg: com.abc.springpackage changed to com.bbc.spring

如果您有机会使用 java 进行配置,bean如果您有包级别更改,您可能需要检查以下声明。例如:com.abc.spring包更改为com.bbc.spring

@Bean
    public SessionFactory sessionFactory() {

        LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
        //builder.scanPackages("com.abc.spring");    //Comment this line as this package no longer valid.
        builder.scanPackages("com.bbc.spring");
        builder.addProperties(getHibernationProperties());

        return builder.buildSessionFactory();
    }

回答by Radhakrishnan

Should use Entity class name for em.createQuery method or Should use em.createNativeQuery method for native query without entity class

应该对 em.createQuery 方法使用实体类名,或者应该对没有实体类的本机查询使用 em.createNativeQuery 方法

With Entity class:

使用实体类:

em.createQuery("select first_name from CUSTOMERV")

em.createQuery("从 CUSTOMERV 中选择 first_name")

Without Entity class or Native query:

没有实体类或本机查询:

em.createNativeQuery("select c.first_name from CUSTOMERV c")

em.createNativeQuery("从 CUSTOMERV c 中选择 c.first_name")