org.hibernate.hql.internal.ast.QuerySyntaxException:用户未映射[来自User],其中User是我的bean类

时间:2014-09-23 05:38:35

标签: hibernate exception gwt

我正在使用hwtnate与gwt,所以我想从表中检索数据,我已经创建了一个DTO类和一个简单的java类,我在其中初始化了DTO对象。

在服务器端,我将结果存储在数组列表中,而不是使用每个循环将查询结果存储到用户类型中,而不是使用DTO对象调用私有方法。

我的代码很好,但是低于异常......并且正在检索我正在解雇"来自用户"查询User是我的简单bean类

这是我的hibernate.cfg.xml文件

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/rs</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.release_mode">auto</property>
        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">10</property>

        <!-- MySQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.hbm2ddl.import_files"></property>

        <!-- Names the annotated entity class -->
         <mapping class="com.valto.querybrowser.client.model.User"/>
        <mapping class="com.valto.querybrowser.client.model.UserDTO"/>

    </session-factory>
</hibernate-configuration>

这是我的DTO类UserDTO.java

    @Entity(name="usertable")
    @Table(name="usertable")
    public class UserDTO implements Serializable{ 
        private static final long serialVersionUID = -5753020447289277291L;

        @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
        @Column(name="userId")
        private int id;
        @Column(name="user_name")
        private String user_name;

        public UserDTO()
        {

        }
        public UserDTO(int id)
        {
            this.id=id;

        }
        public UserDTO(int id,String user_name)
        {
            this.id=id;
            this.user_name=user_name;

        }

        public int getId() {
            return id;
        }
        public void setId(int id) {
            this.id = id;
        }
        public String getUser_name() {
            return user_name;
        }
        public void setUser_name(String user_name) {
            this.user_name = user_name;
        }


    }

这是我的简单bean类User.java

public class User {

    public int id;
    public String user_name;
    public User(UserDTO udto)
    {
        id=udto.getId();
        user_name=udto.getUser_name();
    }
}

这是我的服务器端代码..

@Override
    public List<UserDTO> getUsers(String getInput) throws IllegalArgumentException {

        Session session = SessionFacoryCode.getSessionFactory().openSession();
        System.out.println(getInput+"\n");


        try {
            session.beginTransaction();
             List<User> user = new ArrayList<User>(session.createQuery(getInput).list());
                List<UserDTO> userdto = new ArrayList<UserDTO>(user != null ? user.size() : 0);
                if (user != null) {
                  for (User user1 : user) {
                  userdto.add(createUserDTO(user1));
                  }
                }
            session.getTransaction().commit();
            return userdto;


        } catch (Exception e) {
            getInput=null;
            e.printStackTrace();
            return null;
        } finally {
            session.close();
        }

    }

    private UserDTO createUserDTO(User user1) {

        return new UserDTO(user1.id,user1.user_name);
    }

这是我的SessionfactoryCode.java

public class SessionFacoryCode {
    private static final SessionFactory sessionFactory;

    static {
            try {
                Configuration cfg = new Configuration().configure();         
                ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
               . applySettings(cfg.getProperties()).buildServiceRegistry();
                sessionFactory =cfg.buildSessionFactory(serviceRegistry);



            } catch (Throwable th) {
                    System.err.println("Enitial SessionFactory creation failed" + th);
                    throw new ExceptionInInitializerError(th);
            }
    }
    public static SessionFactory getSessionFactory() {
            return sessionFactory;
    }

}

这是在User.java中添加@Entity后的错误...

Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.valto.querybrowser.client.model.User
    at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:277)
    at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:224)
    at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:665)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3533)
    at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3487)
    at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1376)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1777)
    at com.valto.querybrowser.client.model.SessionFacoryCode.<clinit>(SessionFacoryCode.java:16)
    ... 36 more
[ERROR] 500 - POST /querybrowser/greet (127.0.0.1) 57 bytes
   Request headers
      Host: 127.0.0.1:8888
      Connection: keep-alive
      Content-Length: 145
      X-GWT-Module-Base: http://127.0.0.1:8888/querybrowser/
      X-GWT-Permutation: HostedMode
      Origin: http://127.0.0.1:8888
      User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
      Content-Type: text/x-gwt-rpc; charset=UTF-8
      Accept: */*
      Referer: http://127.0.0.1:8888/QueryBrowser.html?gwt.codesvr=127.0.0.1:9997
      Accept-Encoding: gzip,deflate
      Accept-Language: en-GB,en-US;q=0.8,en;q=0.6
   Response headers
      Content-Type: text/plain
   [WARN] Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.util.List com.valto.querybrowser.client.GreetingService.gettableNames() throws java.lang.IllegalArgumentException' threw an unexpected exception: java.lang.NoClassDefFoundError: Could not initialize class com.valto.querybrowser.client.model.SessionFacoryCode
    at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:389)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:579)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:265)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:305)
    at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:755)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
    at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:686)
    at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:501)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:137)
    at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:557)
    at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
    at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1086)
    at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:428)
    at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:193)
    at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1020)
    at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:135)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.handler.RequestLogHandler.handle(RequestLogHandler.java:68)
    at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:116)
    at org.eclipse.jetty.server.Server.handle(Server.java:370)
    at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:489)
    at org.eclipse.jetty.server.AbstractHttpConnection.content(AbstractHttpConnection.java:960)
    at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.content(AbstractHttpConnection.java:1021)
    at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:865)
    at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)
    at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:82)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:668)
    at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:52)
    at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)
    at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)
    at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: Could not initialize class com.valto.querybrowser.client.model.SessionFacoryCode
    at com.valto.querybrowser.server.GreetingServiceImpl.gettableNames(GreetingServiceImpl.java:33)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:561)
    ... 30 more

3 个答案:

答案 0 :(得分:0)

User is not mapped [from User]这意味着hibernate不知道实体User是什么,因此请将您的User实体包含在Hibernate配置文件中 - hibernate.cfg.xml file

例如:

<mapping class="mypackage.User"/>

您还缺少@Entity课程的User声明。因此,为@Entity类添加注释User

@Entity
@Table(name="T_USER")
public class User {
...
}

某些数据库将USER作为保留关键字,因此请尝试使用@Table注释提供不同的表名。

更新:

现在错误显示Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.valto.querybrowser.client.model.User,表示您在User类中没有任何表示标识符的字段,这在hibernate中是必需的。因此,只需为id添加User字段UserDTO所需的注释,例如:

@Entity
@Table(name="T_USER")
public class User {
   @Id @GeneratedValue(strategy=GenerationType.IDENTITY)
   private int id;
   ...
}

答案 1 :(得分:0)

这段代码实际上是导致问题的。

List<User> user = new ArrayList<User>(session.createQuery(getInput).list());

您正在尝试从数据库中获取列表,并且您没有将表映射到User

需要为@Entity添加

User.java

答案 2 :(得分:0)

用户未映射[来自用户]这意味着hibernate不知道实体用户是什么,因此请将您的用户实体包含在Hibernate配置文件--hibernate.cfg.xml文件中或检查您是否可能做了一些拼写错误或其他内容