Org.hibernate.hql.internal.ast.QuerySyntaxException: таблица не отображается
У меня есть пример веб-приложения Hibernate 4.3.5 + база данных Derby 10.10.1.1+ Glassfish4.0 с IDE NetBeans 8.0Beta.
У меня есть следующее исключение:
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>
Customer.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>
Ответы
Ответ 1
Наконец я нашел ошибку! Надеюсь, это кому-то полезно. Когда вы делаете запрос к базе данных (в моем случае это Apache Derby), имя базы нужно написать в первом случае верхний регистр первой буквы.
Это неправильный запрос:
session.createQuery("select first_name from CUSTOMERV").
Это действительный запрос
session.createQuery("select first_name from Customerv").
И объект класса должен иметь то же имя, что и база данных, но я не уверен.
Ответ 2
Файл hibernate.cfg.xml должен иметь сопоставление для таблиц, как показано ниже. Проверьте, нет ли в вашем файле.
......
<hibernate-configuration>
......
......
<session-factory>
......
<mapping class="com.test.bean.dbBean.testTableHibernate"/>
......
</session-factory>
</hibernate-configuration>
.....
Ответ 3
В запросе hql не записывается имя таблицы, введите имя объекта сущности в ваш запрос, например
String s = "from entity_cllass name";
query qry = session.createUqery(s);
Ответ 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 {
...
}
Ответ 5
Есть еще один шанс получить это исключение, даже если мы использовали имя класса, т.е. если у нас есть два класса с одинаковым именем в разных пакетах. мы получим эту проблему.
Я думаю, что hibernate может получить двусмысленность и выбрасывает это исключение, поэтому решение должно использовать полное квалифицированное имя (например, com.test.Customerv)
Я добавил этот ответ, который поможет в сценарии, как я уже упоминал. У меня такой же сценарий застрял в течение некоторого времени.
Ответ 6
Другие лица, которые используют классы отображения для Hibernate, должны убедиться, что они правильно обратились к образцу пакета в sessionFactory
bean-компонента sessionFactory
в следующей части:
<property name="packagesToScan" value="com.mblog.model"></property>
Ответ 7
Ни одно другое решение не работало для меня.
Даже если я не думаю, что это лучшая практика, я должен был добавить ее в код, подобный этому
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;
}
Ответ 8
Если вы случайно используете 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();
}
Ответ 9
Это означает, что ваша таблица не привязана к JPA. Либо имя таблицы неверно (возможно, с учетом регистра), либо вам нужно поместить запись в файл XML.
Счастливое кодирование :)
Ответ 10
Если вы используете аннотации JPA для создания сущностей, а затем убедитесь, что имя таблицы сопоставлено с аннотацией @Table вместо @Entity.
Неверно нанесенный на карту:
@Entity(name="DB_TABLE_NAME")
public class DbTableName implements Serializable {
....
....
}
Правильно сопоставленная сущность:
@Entity
@Table(name="DB_TABLE_NAME")
public class DbTableName implements Serializable {
....
....
}
Ответ 11
Проблема частично была решена. Кроме того, для создания jdbc/resource (DB Derby) пришлось создать пул соединений JDBC для ресурса db в консоли администратора Glassfish и проверить его на ping. Теперь вся работа CRUD работает нормально. Я проверяю, объект Customer в базе данных правильно добавляет, обновляет и удаляет. Но в журнале журналов 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)
Ответ 12
Должно использовать имя класса Entity для метода em.createQuery или использовать метод em.createNativeQuery для собственного запроса без класса сущности
С классом Entity:
em.createQuery("выберите first_name из CUSTOMERV")
Без класса Entity или собственного запроса:
em.createNativeQuery("выберите c.first_name из CUSTOMERV c")
Ответ 13
В моем случае: spring boot 2, множественный источник данных (по умолчанию и пользовательский). entityManager.createQuery
ошибочно: "объект не отображается"
в то время как debug, я узнаю, что unitManager unitManame ошибочен (должен быть обычным, но факт по умолчанию) правильным способом:
@PersistenceContext(unitName = "customer1") // !important,
private EntityManager em;
customer1
является вторым классом конфигурации datasource:
@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 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
- из второго класса конфигурации datasource:
@Bean(name = "customer1TransactionManager")
public PlatformTransactionManager transactionManager(
@Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
Весь второй конфигурационный класс datasource:
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 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);
}
}
Ответ 14
В этой статье мы обсуждаем hibernate org.hibernate.hql. Ast.QuerySyntaxException Решение. Это исключение очень распространено, если вы новичок в создании приложения гибернации.
Исключение Stacktrace:
Exception in thread "main" org.hibernate.hql.ast.QuerySyntaxException:
employee is not mapped [from employee]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:111)
at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:93)
at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:327)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3441)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3325)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:733)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:584)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:301)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:244)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:124)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1770)
at com.payroll.EmployeeDeatails.main(EmployeeDeatails.java:21)
Причина исключения
Вышеуказанное QuerySyntaxException генерируется, когда мы неправильно отображаем имя таблицы. Новички в hibernate могут столкнуться с этой ошибкой, потому что вы, люди, сопоставите имя таблицы непосредственно в вашем запросе. Этот запрос не будет работать в Hibernate Framework. Вам нужно будет сопоставить имя класса, которое отображается в файле конфигурации Hibernate. Смотрите следующий пример:
Юридическое лицо сотрудника:
@Entity
@Table(name = "employee", schema = "payroll")
public class Employee{
int id;
String name;
String department;
//getters and setters
}
Код гибернации:
public static void main(String[] args)
{
//Creating session factory object
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//Getting session object from session factory object
Session session = sessionFactory.openSession();
//Getting transaction object from session object
session.beginTransaction();
Query query = session.createQuery("from employee");
List<Employee> employees = query.list();
for(Employee emp1 : employees)
{
System.out.println("eid: "+emp1.getId()+", Employee Name: "+emp1.getName()+", Department: "+emp1.getDepartment());
}
session.getTransaction().commit();
sessionFactory.close();
}
Описание
Этот запрос не является запросом SQL. Здесь вы используете HQL-запрос. Таким образом, вы не должны использовать имена таблиц, но имена классов сущностей ("от сотрудника" вместо "от сотрудника"). Здесь "employee" не является именем сущности, по умолчанию имя сущности совпадает с именем класса, поэтому мы должны использовать "Employee" вместо "employee". HQL автоматически выбирает имя объекта, а не имя таблицы. Поэтому, пожалуйста, будьте осторожны с этой проблемой.
Query query = session.createQuery("from employee"); // Exception is thrown
Решение
Если вы используете следующий код, то вы успешно запустились.
public static void main(String[] args)
{
//Creating session factory object
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
//Getting session object from session factory object
Session session = sessionFactory.openSession();
//Getting transaction object from session object
session.beginTransaction();
Query query = session.createQuery("from Employee");//Here the class names is case sensitive.
List<Employee> employees = query.list();
for(Employee emp1 : employees)
{
System.out.println("eid: "+emp1.getId()+", Employee Name: "+emp1.getName()+", Department: "+emp1.getDepartment());
}
session.getTransaction().commit();
sessionFactory.close();
}
Чтобы получить более подробную информацию, нажмите: https://www.quora.com/How-can-I-do-to-automatics-reset-auto-increment-values-in-MySQL-table/answer/Shadab-Kazi-17
Ответ 15
В Apache Derby DB воздерживайтесь от использования имен таблиц в качестве "пользователя" или около того, потому что они являются зарезервированными ключевыми словами в Apache Derby, но будут отлично работать на MySql.
В запросе вы должны указать имя класса Entity, из которого вы хотите извлечь данные, в предложении FROM запроса.
List<User> users=session.createQuery("from User").list();
Здесь User - это имя моего класса Java Entity (Рассмотрим регистр имени, поскольку в Java это имеет значение.)
Ответ 16
Я тоже столкнулся с подобной проблемой, когда начал работать над Hibernate. В общем, я могу сказать, что в createQuery нужно передать имя класса сущности, а не имя таблицы, в которую отображается сущность.