2012-03-31 46 views
87

我試圖讓所有從「用戶」表中的用戶的列表,並且我收到以下錯誤:休眠錯誤 - QuerySyntaxException:用戶並非[從用戶]映射

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配置文件:

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

,這是我的用戶等級:

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

任何想法,爲什麼我得到這個錯誤?

+1

相關:http://stackoverflow.com/questions/14446048/hibernate-table-not-mapped-error – Gray 2016-07-20 15:48:12

回答

211

在HQL,你應該使用Java類名和映射@Entity而不是實際的表名和列名的屬性名稱,所以HQL應該是:

List<User> result = (List<User>) session.createQuery("from User").list(); 
+5

所以實際上這甚至是大小寫敏感的。所以「從用戶」將導致相同的異常 – tObi 2014-07-11 12:25:46

+1

它是答案的一部分,但要解決這個錯誤,我不得不使用像這樣的完整的對象路徑:[...]。createQuery(「from gcv.metier.User作爲你在哪裏u.username =?「) – Raphael 2015-10-02 00:13:56

11

只是爲了分享我的發現。即使查詢的目標是正確的類名,我仍然遇到同樣的錯誤。後來我意識到我正在從錯誤的包中導入實體類。

import org.hibernate.annotations.Entity; 

import javax.persistence.Entity; 
+0

它爲我工作。 – PKTomar 2017-05-20 13:00:26

7

新增@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; 
    } 
} 
+0

請考慮削減您的代碼示例。 – Gray 2016-07-20 15:44:13

4

有你忘了爲創建實體添加映射到hibernate.cfg.xml,同樣的錯誤可能性。

+0

我也忘了在hibernate.cfg.xml中添加POJO類。 – Chinmoy 2018-02-27 06:09:17

13

例如:你的bean類名稱爲的UserDetails

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

您不要在數據庫給你的表名。 給你豆類名稱

2

我也被導入錯誤的實體import org.hibernate.annotations.Entity; 它應該是進口javax.persistence.Entity;

5

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

這表明Hibernate不知道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{ 

見我的答案在這裏獲得更多信息:Hibernate table not mapped error

3

也檢查你使用添加了註解類:

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

當我在數據庫中使用Hibernate添加一個新表時,總是浪費我的時間。

5

還要確保以下屬性在Hibernate 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) 
+0

你確定「基於Linux的MySQL」在這裏有作用嗎? – asgs 2017-11-23 20:32:59

0

我在用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); 

    } 
} 

希望它可以幫助別人