休眠错误-QuerySyntaxException:[未从用户映射用户]


126

我试图从“用户”表中获取所有用户的列表,但出现以下错误:

org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users]
org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:180)
org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:110)
org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:93)

这是我编写的用于添加/获取用户的代码:

public List<User> getUsers() {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    List<User> result = (List<User>) session.createQuery("from users").list();
    session.getTransaction().commit();
    return result;
}

public void addUser(User user) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    session.save(user);
    session.getTransaction().commit();
}

public void addUser(List<User> users) {
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
    session.beginTransaction();
    for (User user : users) {
        session.save(user);
    }
    session.getTransaction().commit();
}

添加用户是可行的,但是当我使用getUsers函数时,出现这些错误。

这是我的休眠配置文件:

<hibernate-configuration>
<session-factory>
    <property name="connection.url">jdbc:mysql://localhost:3306/test</property>
    <property name="connection.username">root</property>
    <property name="connection.password">root</property>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.default_schema">test</property>
    <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>

    <property name="show_sql">true</property>

    <property name="format_sql">true</property>
    <property name="hbm2ddl.auto">create-drop</property>

    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <property name="current_session_context_class">thread</property>

    <!-- Mapping files will go here.... -->

    <mapping class="model.Company" />
    <mapping class="model.Conference" />
    <mapping class="model.ConferencesParticipants" />
    <mapping class="model.ConferenceParticipantStatus" />
    <mapping class="model.ConferencesUsers" />
    <mapping class="model.Location" />
    <mapping class="model.User" />

</session-factory>

这是我的User类:

@Entity
@Table( name = "Users" )
public class User implements Serializable{

    private long userID;
    private int pasportID;
    private Company company; 
    private String name;
    private String email;
    private String phone1;
    private String phone2;
    private String password; //may be null/empty , will be kept hashed
    private boolean isAdmin;
    private Date lastLogin;

    User() {} //not public on purpose!

    public User(int countryID, Company company, String name, String email,
            String phone1, String phone2, String password, boolean isAdmin) {
        this.pasportID = countryID;
        this.company = company;
        this.name = name;
        this.email = email;
        this.phone1 = phone1;
        this.phone2 = phone2;
        this.password = password;
        this.isAdmin = isAdmin;
    }

    @Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
    public long getUserID() {
        return userID;
    }
    public void setUserID(long userID) {
        this.userID = userID;
    }
    ...    
}

知道为什么我会收到此错误吗?


Answers:


297

在HQL中,应该使用映射的java类名属性名@Entity而不是实际的表名和列名,因此HQL应该为:

List<User> result = session.createQuery("from User", User.class).getResultList();

更新:更精确地说,您应该使用在中配置的实体名称@Entity来引用“表”,如果未明确设置,则默认为映射的Java类的非限定名称。

(PS是@javax.persistence.Entity但不是@org.hibernate.annotations.Entity


10
因此,实际上这是区分大小写的。因此“来自用户”将导致相同的例外
tObi 2014年

3
这是答案的一部分,但是要解决错误,我必须使用完整的对象路径,如下所示:[...]。createQuery(“来自gcv.metier.User,来自u,其中u.username =?”)
Raphael

我还必须使用整个路径,也许JPA的“用户”一词有问题?我猜这是一些数据库实现中的保留字。实际上,这个问题只是在我将JPA没问题之前将数据库表从用户重命名为the_user(修复另一个问题的一部分)时才出现。
Michael Coxon

1
您可以将不赞成将list()更新为getResultList()吗?
Durja Arai

31

例如:您的bean类名称是UserDetails

Query query = entityManager. createQuery("Select UserName from **UserDetails** "); 

您不在Db上提供表名。您给出bean的类名


12

只是分享我的发现。即使查询的目标是正确的类名,我仍然遇到相同的错误。后来我意识到我是从错误的包中导入Entity类。

从以下位置更改导入行后,问题已解决:

import org.hibernate.annotations.Entity;

import javax.persistence.Entity;

现在,这实际上救了我。
Anirudh

9

添加@TABLE(name = "TABLE_NAME")注释并修复。检查您的注释和hibernate.cfg.xml文件。这是有效的示例实体文件:

import javax.persistence.*;

@Entity
@Table(name = "VENDOR")
public class Vendor {

    //~ --- [INSTANCE FIELDS] ------------------------------------------------------------------------------------------
    private int    id;
    private String name;

    //~ --- [METHODS] --------------------------------------------------------------------------------------------------
    @Override
    public boolean equals(final Object o) {    
        if (this == o) {
            return true;
        }

        if (o == null || getClass() != o.getClass()) {
            return false;
        }

        final Vendor vendor = (Vendor) o;

        if (id != vendor.id) {
            return false;
        }

        if (name != null ? !name.equals(vendor.name) : vendor.name != null) {
            return false;
        }

        return true;
    }

    //~ ----------------------------------------------------------------------------------------------------------------
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Id
    public int getId() {
        return id;
    }

    @Basic
    @Column(name = "NAME")
    public String getName() {

        return name;
    }

    public void setId(final int id) {
        this.id = id;
    }

    public void setName(final String name) {    
        this.name = name;
    }

    @Override
    public int hashCode() {
        int result = id;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        return result;
    }
}

8

您可能忘记将创建的实体的映射添加到hibernate.cfg.xml,同样的错误。


我也忘记在hibernate.cfg.xml中添加POJO类。
Chinmoy

6

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

这表明休眠状态不将该User实体称为“用户”。

@javax.persistence.Entity
@javax.persistence.Table(name = "Users")
public class User {

@Table注释设置的名称是“用户”,但实体名称仍然指在HQL“用户”。

要同时更改两者,应设置实体名称:

// this sets the name of the table and the name of the entity
@javax.persistence.Entity(name = "Users")
public class User implements Serializable{

有关更多信息,请参见我的回答:休眠表未映射错误


5

还要确保在您的休眠bean配置中设置了以下属性:

<property name="packagesToScan" value="yourpackage" />

这告诉spring和hibernate在哪里找到标注为实体的域类。


5

一些基于Linux的MySQL安装要求区分大小写。解决方法是申请nativeQuery

@Query(value = 'select ID, CLUMN2, CLUMN3 FROM VENDOR c where c.ID = :ID', nativeQuery = true)

1
您确定“基于Linux的MySQL”在这里有作用吗?
asgs

3

我也导入了错误的实体import org.hibernate.annotations.Entity; ,应该导入javax.persistence.Entity;


3

还要使用以下命令检查是否添加了带注释的类:

new Configuration().configure("configuration file path").addAnnotatedClass(User.class)

使用Hibernate在数据库中添加新表时,这总是浪费我的时间。


2

我在使用hibernate的Spring中遇到了相同的错误。我在createQuery语句的小写字母中使用了“ user”,而我的类是User..So,因此在查询中将其更改为User并解决了问题。

之前查询:

Query query= em.createQuery("select u from user u where u.username=:usr AND u.password=:pass",User.class);

查询后:

Query query= em.createQuery("select u from User u where u.username=:usr AND u.password=:pass",User.class);

1

当我用hibernate-core-5.2.12替换旧的hibernate-core库时,出现了这个问题。但是我所有的配置都还可以。我通过这样创建sessionfactory来解决此问题:

private static SessionFactory buildsSessionFactory() {
    try {
        if (sessionFactory == null) {
            StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                    .configure("/hibernate.cfg.xml").build();
            Metadata metaData = new MetadataSources(standardRegistry)
                    .getMetadataBuilder().build();
            sessionFactory = metaData.getSessionFactoryBuilder().build();
        }
        return sessionFactory;
    } catch (Throwable th) {

        System.err.println("Enitial SessionFactory creation failed" + th);

        throw new ExceptionInInitializerError(th);

    }
}

希望对别人有帮助


1

我推荐这种模式:

@Entity(name = User.PERSISTANCE_NAME)
@Table(name = User.PERSISTANCE_NAME )
public class User {    
    static final String PERSISTANCE_NAME = "USER";

    // Column definitions here

}

0

在您的查询中,您必须使用类名(用户)而不是表名(用户),因此您的查询是“来自用户”



0

使用 org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users],您正尝试从users表格中选择。但是您正在使用注释您的课程@Table( name = "Users" )。因此,请使用usersUsers


0

如果使用xml配置,则applicationContext.xml文件中将需要以下内容:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" lazy-init="default" autowire="default" dependency-check="default">
<property name="dataSource">
  <ref bean="dataSource" />
</property>
<property name="annotatedClasses">
  <list>
    <value>org.browsexml.timesheetjob.model.PositionCode</value>
  </list>
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.