program tip

HQL 쿼리에서 Hibernate 테이블이 매핑되지 않음 오류

radiobox 2020. 12. 29. 06:55
반응형

HQL 쿼리에서 Hibernate 테이블이 매핑되지 않음 오류


Hibernate를 사용하여 데이터베이스를 통해 CRUD 작업을 수행하는 웹 응용 프로그램이 있습니다. 테이블이 매핑되지 않았다는 오류가 발생했습니다. Java 파일을 참조하십시오.

에러 메시지:

org.springframework.orm.hibernate3.HibernateQueryException: Books is not mapped [SELECT COUNT(*) FROM Books]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: Books is not mapped [SELECT COUNT(*) FROM Books]
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:660)
at org.springframework.orm.hibernate3.HibernateAccessor.convertHibernateAccessException(HibernateAccessor.java:412)
at org.springframework.orm.hibernate3.HibernateTemplate.doExecute(HibernateTemplate.java:411)
...
Caused by: org.hibernate.hql.ast.QuerySyntaxException: Books is not mapped [SELECT COUNT(*) FROM Books]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:181)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:111)
at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:93)
...

DAO.java방법은 다음과 같습니다 .

public int getTotalBooks(){
    return DataAccessUtils.intResult(hibernateTemplate.find(
          "SELECT COUNT(*) FROM Books"));
}

Book.java:

@Entity
@Table(name="Books")
public class Book {

    @Id
    @GeneratedValue
    @Column(name="id")
    private int id;

    @Column(name="title", nullable=false)
    private String title;
    ...
}

작동하려면 어떻게 수정해야합니까?


예외 메시지는 무엇을 말합니까? 그것은 말한다 :

Books is not mapped [SELECT COUNT(*) FROM Books]; nested exception is org.hibernate.hql.ast.QuerySyntaxException: Books is not mapped [SELECT COUNT(*) FROM Books]

그것은 당신에게 무엇을 말합니까? 그것은 Books매핑되지 않았다는 것을 알려줍니다 . 즉,라는 매핑 된 유형이 없습니다 Books.

그리고 실제로는 없습니다. 매핑 된 유형은라고 Book합니다. 라는 테이블에 매핑 Books되지만 유형은라고 Book합니다. HQL (또는 JPQL) 쿼리를 작성할 때 테이블이 아닌 유형의 이름을 사용합니다.

따라서 쿼리를 다음과 같이 변경하십시오.

select count(*) from Book

필요하다고 생각하지만

select count(b) from Book b

HQL이 *표기법을 지원하지 않는 경우 .

예외 메시지를 읽고 배울 수있는 것이 많습니다!


hibernate3.HibernateQueryException: Books is not mapped [SELECT COUNT(*) FROM Books];

Hibernate는 "Books"라는 이름의 엔티티를 모른다고 말하려고합니다. 엔티티를 살펴 보겠습니다.

@javax.persistence.Entity
@javax.persistence.Table(name = "Books")
public class Book {

권리. 에 대한 테이블 이름은 Book"Books"로 이름이 바뀌었지만 엔티티 이름은 여전히 ​​클래스 이름에서 "Book"입니다. 엔티티 이름을 설정하려면 @Entity대신 주석의 이름을 사용해야합니다 .

// this allows you to use the entity Books in HQL queries
@javax.persistence.Entity(name = "Books")
public class Book {

그러면 엔티티 이름과 테이블 이름이 모두 설정됩니다.


Person.hbm.xml파일에서 최대 절전 필드를 설명하기 위해 Java 주석을 사용하는 것으로 마이그레이션 할 때 반대 문제가 발생했습니다 . 내 이전 XML 파일은 다음과 같습니다.

<hibernate-mapping package="...">
    <class name="Person" table="persons" lazy="true">
       ...
</hibernate-mapping>

그리고 내 새 엔티티에는 @Entity(name=...)테이블 이름을 설정하는 데 필요한 것이 있습니다.

// this renames the entity and sets the table name
@javax.persistence.Entity(name = "persons")
public class Person {
    ...

그때 내가 본 것은 다음과 같은 HQL 오류였습니다.

QuerySyntaxException: Person is not mapped
     [SELECT id FROM Person WHERE id in (:ids)]

The problem with this was that the entity name was being renamed to persons as well. I should have set the table name using:

// no name = here so the entity can be used as Person
@javax.persistence.Entity
// table name specified here
@javax.persistence.Table(name = "persons")
public class Person extends BaseGeneratedId {

Hope this helps others.


This answer comes late but summarizes the concept involved in the "table not mapped" exception(in order to help those who come across this problem since its very common for hibernate newbies). This error can appear due to many reasons but the target is to address the most common one that is faced by a number of novice hibernate developers to save them hours of research. I am using my own example for a simple demonstration below.

The exception:

org.hibernate.hql.internal.ast.QuerySyntaxException: subscriber is not mapped [ from subscriber]

In simple words, this very usual exception only tells that the query is wrong in the below code.

Session session = this.sessionFactory.getCurrentSession();
List<Subscriber> personsList = session.createQuery(" from subscriber").list();

This is how my POJO class is declared:

@Entity
@Table(name = "subscriber")
public class Subscriber

But the query syntax "from subscriber" is correct and the table subscriber exists. Which brings me to a key point:

  • It is an HQL query not SQL.

and how its explained here

HQL works with persistent objects and their properties not with the database tables and columns.

Since the above query is an HQL one, the subscriber is supposed to be an entity name not a table name. Since I have my table subscriber mapped with the entity Subscriber. My problem solves if I change the code to this:

Session session = this.sessionFactory.getCurrentSession();
List<Subscriber> personsList = session.createQuery(" from Subscriber").list();

Just to keep you from getting confused. Please note that HQL is case sensitive in a number of cases. Otherwise it would have worked in my case.

Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.

https://www.tutorialspoint.com/hibernate/hibernate_query_language.htm

To further understand how hibernate mapping works, please read this


Thanks everybody. Lots of good ideas. This is my first application in Spring and Hibernate.. so a little more patience when dealing with "novices" like me..

Please read Tom Anderson and Roman C.'s answers. They explained very well the problem. And all of you helped me.I replaced

SELECT COUNT(*) FROM Books

with

select count(book.id) from Book book

And of course, I have this Spring config:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan" value="extjs.model"/>

Thank you all again!


In the Spring configuration typo applicationContext.xml where the sessionFactory configured put this property

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="packagesToScan" value="${package.name}"/>

Hibernate also is picky about the capitalization. By default it's going to be the class name with the First letter Capitalized. So if your class is called FooBar, don't pass "foobar". You have to pass "FooBar" with that exact capitalization for it to work.


In addition to the accepted answer, one other check is to make sure that you have the right reference to your entity package in sessionFactory.setPackagesToScan(...) while setting up your session factory.

ReferenceURL : https://stackoverflow.com/questions/14446048/hibernate-table-not-mapped-error-in-hql-query

반응형