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


96

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

我有下一个例外:

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 

来自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> 

客户.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

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

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

Answers:


120

最后我发现了一个错误!希望这对某人有用。对数据库(在我的情况下为Apache Derby)进行请求时,基本名称需要将首字母大写,小写。

这是错误的查询:

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

这是有效的查询

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

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


44
那可能不是原因。在Customer c中选择c,这是很好的查询,因为Customer是您的类名,我们应该在查询中写类名,而不是表名。在hibernate.cfg.xml中,您只给了<mapping resource and class>一个会没事的。请检查一下。
Shoaib Chikate 2014年

感谢您的建议Shoalib Chikate!
弗拉德·多布里丹


4
太好了,对我有用的一件事就是使用格式正确的类名,而不是数据库表名本身。我认为Hibernate要求它能够进行正确的映射。这有点令人困惑,虽然不是JDBC的通常方式,但是我希望将来的版本会喜欢这个问题。对于其中的某些查询机制,保留JDBC的某些样式将是一个加号。
阿卡

2
谢谢。它为我工作。实际上,它采用实体/类名而不是表名。例如:如果您的表名是CUSTOMER,而您的实体名是Customer,那么它将是Customer,因为它是HQL查询。
特里

50

HQL查询中,不要写表名,在查询中 写您的Entity类名

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

您节省了我的时间和生命(*> *)
Ved Prakash

19

就我而言,我只是忘记添加 nativeQuery = true

@Query( value = "some sql query ...", nativeQuery = true)

对于使用Spring Data JPA的Spring Boot


1
谢谢!我现在也发生了同样的事情:)
essayoub

12

hibernate.cfg.xml文件应该具有如下表的映射。检查文件中是否缺少该文件。

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

</hibernate-configuration>
.....

1
对于我来说就是这种情况,同时将实现更改为可与Oracle DB代替Derby一起使用-与Derby一起,由于某种原因,不需要在persistence.xml中声明实体(对我来说,这是合乎逻辑的,因为实体已经被注释了)(也许那是因为驱动程序(ojdbc6)较旧)
hello_earth

9

如果使用JPA批注创建实体,然后确保表名与@Table批注而不是@Entity一起映射。

映射不正确:

@Entity(name="DB_TABLE_NAME")
public class DbTableName implements Serializable {
   ....
   ....
}

正确映射的实体:

@Entity
@Table(name="DB_TABLE_NAME")
public class DbTableName implements Serializable {
   ....
   ....
}

3
谢谢!那正是我对这个问题的看法。
Martin McCallion

1
谢谢非常有帮助。继续帮助他人
mukesh krishnan

4

也许这将使其更加清晰,当然也很有意义。

@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 {
...
}

3

即使我们使用类名,也有机会获得此异常,即,如果我们在不同的包中有两个具有相同名称的类。我们会解决这个问题。

我认为休眠可能会变得模棱两可并引发此异常,因此解决方案是使用完整的限定名称(例如com.test.Customerv

我添加了这个答案,将在我提到的场景中提供帮助。我遇到了相同的情况,已经停留了一段时间。


3

没有其他解决方案对我有用。

即使我不认为它的最佳实践,我不得不把它添加到代码这样

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

这里

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;
}

3

当我开始在Hibernate上工作时,我也遇到过类似的问题。我可以说的全部是在createQuery中,需要传递实体类的名称而不是实体映射到的表名称。



2

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

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

我曾就此问题与micronaut当我忘了改packages-to-scan我的application.yml配置文件。
Ibrahim.H

1

如果您偶然使用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();
    }

1

在我的情况下:spring boot 2,多个数据源(默认和自定义)。entityManager.createQuery出错:“实体未映射”

在调试时,我发现正确的方法是EntityManager的unitName是错误的(应该是自定义的,但事实是默认的):

@PersistenceContext(unitName = "customer1") // !important, 
private EntityManager em;

customer1是从第二数据源配置类:

@Bean(name = "customer1EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
        @Qualifier("customer1DataSource") DataSource dataSource) {
    return builder.dataSource(dataSource).packages("com.xxx.customer1Datasource.model")
            .persistenceUnit("customer1")
            // PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
            // injects an EntityManager.
            // It's generally better to use PersistenceContext unless you really need to
            // manage the EntityManager lifecycle manually.
            // 【4】
            .properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
}

然后,entityManager是正确的。

但是,em.persist(entity)不起作用,并且事务也不起作用。

另一个要点是:

@Transactional("customer1TransactionManager") // !important
public Trade findNewestByJdpModified() {
    //test persist,working right!
    Trade t = new Trade();
    em.persist(t);
    log.info("t.id" + t.getSysTradeId());

    //test transactional, working right!
    int a = 3/0;
}

customer1TransactionManager 来自第二个数据源配置类:

@Bean(name = "customer1TransactionManager")
public PlatformTransactionManager transactionManager(
        @Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
}

整个第二个数据源配置类是:

package com.lichendt.shops.sync;

import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(entityManagerFactoryRef = "customer1EntityManagerFactory", transactionManagerRef = "customer1TransactionManager",
        // 【1】这里写的是DAO层的路径 ,如果你的DAO放在 com.xx.DAO下面,则这里写成 com.xx.DAO
        basePackages = { "com.lichendt.customer1Datasource.dao" })
public class Custom1DBConfig {

    @Autowired
    private JpaProperties jpaProperties;

    @Bean(name = "customer1DatasourceProperties")
    @Qualifier("customer1DatasourceProperties")
    @ConfigurationProperties(prefix = "customer1.datasource")
    public DataSourceProperties customer1DataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "customer1DataSource")
    @Qualifier("customer1DatasourceProperties")
    @ConfigurationProperties(prefix = "customer1.datasource") //
    // 【2】datasource配置的前缀,对应上面 【mysql的yaml配置】
    public DataSource dataSource() {
        // return DataSourceBuilder.create().build();
        return customer1DataSourceProperties().initializeDataSourceBuilder().build();
    }

    @Bean(name = "customer1EntityManagerFactory")
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
            @Qualifier("customer1DataSource") DataSource dataSource) {
        return builder.dataSource(dataSource).packages("com.lichendt.customer1Datasource.model") // 【3】这里是实体类的包路径
                .persistenceUnit("customer1")
                // PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
                // injects an EntityManager.
                // It's generally better to use PersistenceContext unless you really need to
                // manage the EntityManager lifecycle manually.
                // 【4】
                .properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
    }

    @Bean(name = "customer1TransactionManager")
    public PlatformTransactionManager transactionManager(
            @Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
        return new JpaTransactionManager(entityManagerFactory);
    }
}

显示了如何配置多个数据源与springboot 2
hatanooh

0

问题已部分解决。除了创建jdbc / resource(DB Derby)之外,还必须在Glassfish管理控制台中为数据库资源创建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)

1
建议打开一个新问题...这不是第一个问题的答案...或使用“更新”关键字增强您的第一个问题
Pipo

0

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

使用实体类:

em.createQuery(“从CUSTOMERV中选择first_name”)

没有实体类或本机查询:

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


0

在Apache Derby DB中,请勿将表名用作“用户”,因为它们是Apache Derby上的保留关键字,但在MySql上可以正常使用。

在查询中,必须在查询的FROM子句中指定要从中获取数据的Entity类的名称。

List<User> users=session.createQuery("from User").list();

在这里,User是我的Java Entity类的名称(考虑名称的大小写,就像在Java中一样重要。)


0

另一个可行的解决方案:

实际引发此异常的数据访问对象是

public List<Foo> findAll() {
    return sessionFactory.getCurrentSession().createQuery("from foo").list();
}

我在上面的片段中犯的错误是我在createQuery中使用了表名foo。相反,我必须使用实际的类名Foo。

public List<Foo> findAll() {
    return sessionFactory.getCurrentSession().createQuery("from Foo").list();

感谢此博客:https : //www.arundhaj.com/blog/querysyntaxexception-not-mapped.html


0

使用Hibernate映射类的其他人,请确保在以下部分中已正确寻址到sessionFactory bean声明中的模型包:

public List<Book> list() {
    List<Book> list=SessionFactory.getCurrentSession().createQuery("from book").list();
    return list;
}

我在上面的片段中犯的错误是我在createQuery中使用了表名foo。相反,我必须使用实际的类名Foo。

public List<Book> list() {                                                                               
    List<Book> list=SessionFactory.getCurrentSession().createQuery("from Book").list();
    return list;
}

0

添加参数nativeQuery = true

例如:@Query(value =“更新用户集user_name =:user_name,password =:password,其中user_id =:user_id”,nativeQuery = true)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.