GWT Hibernate程序2中的错误

时间:2011-11-24 19:02:10

标签: mysql eclipse hibernate gwt rpc

我设法从帖子stackoverflow post about GWT获取提示来解决此问题。该帖子告诉我,JDBC不应该在客户端,而应在服务器端。

我正在尝试创建一个简单的Web应用程序,使用GWT RPC和Hibernate,MySql& eclipse IDE。我已经有一个简单版本的hibernate程序运行&现在我正在尝试使用GWT RPC做同样的事情。

虽然在使用带有RPC的hibernate时可能存在某些不同的做法。首先,我必须将jar / libs添加到war / web.inf / lib add中,然后再将它们添加到classpath中,同时我在src中创建了一个简单的文件夹,将所有jars / library放到那个&然后添加到classpath中的简单hibernate应用程序。继续,编译器然后引发了关于cfg.xml&的不可用性的错误。映射hibernate文件包中的文件(包含pojo文件)。我把它们移到src文件夹&错误消失了。但现在错误是关于会话创建。这次将Util文件移动到src不起作用。

这是我项目的目录结构:

src
   hbm.xml
   cfg.xml
hibDomain(hibernate package)
rppctest.client (GWT package) 
rppctest.server (GWT package)

我在Windows 7上使用MySQL。 以下是错误消息&我的代码。

错误

94 [btpool0-2] INFO org.hibernate.cfg.Environment - Hibernate 3.3.1.GA
126 [btpool0-2] INFO org.hibernate.cfg.Environment - hibernate.properties not found
173 [btpool0-2] INFO org.hibernate.cfg.Environment - Bytecode provider name : javassist
282 [btpool0-2] INFO org.hibernate.cfg.Environment - using JDK 1.4 java.sql.Timestamp handling
751 [btpool0-2] INFO org.hibernate.cfg.Configuration - configuring from resource: /hibernate.cfg.xml
751 [btpool0-2] INFO org.hibernate.cfg.Configuration - Configuration resource: /hibernate.cfg.xml
3657 [btpool0-2] INFO org.hibernate.cfg.Configuration - Reading mappings from resource : user.hbm.xml
4018 [btpool0-2] INFO org.hibernate.cfg.HbmBinder - Mapping class: com.hib.User -> users
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource user.hbm.xml
Starting Jetty on port 8888
   [WARN] Exception while dispatching incoming RPC call
com.google.gwt.user.server.rpc.UnexpectedException: Service method 'public abstract java.lang.String rpctest.client.RpctestService.addUser(java.lang.String,java.lang.String) throws java.lang.IllegalArgumentException' threw an unexpected exception: java.lang.ExceptionInInitializerError
    at com.google.gwt.user.server.rpc.RPC.encodeResponseForFailure(RPC.java:385)
    at com.google.gwt.user.server.rpc.RPC.invokeAndEncodeResponse(RPC.java:588)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processCall(RemoteServiceServlet.java:208)
    at com.google.gwt.user.server.rpc.RemoteServiceServlet.processPost(RemoteServiceServlet.java:248)
    at com.google.gwt.user.server.rpc.AbstractRemoteServiceServlet.doPost(AbstractRemoteServiceServlet.java:62)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    at org.mortbay.jetty.servlet.ServletHolder.handle(ServletHolder.java:487)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:362)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:181)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:729)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:405)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.handler.RequestLogHandler.handle(RequestLogHandler.java:49)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:324)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:505)
    at org.mortbay.jetty.HttpConnection$RequestHandler.content(HttpConnection.java:843)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:647)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:205)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:380)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:395)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:488)
Caused by: java.lang.ExceptionInInitializerError
    at hibDomain.HibernateUtil.buildSessionFactory(HibernateUtil.java:16)
    at hibDomain.HibernateUtil.<clinit>(HibernateUtil.java:7)
    at rpctest.server.RpctestServiceImpl.addUser(RpctestServiceImpl.java:19)
    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:569)
    ... 22 more
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource user.hbm.xml
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:602)
    at org.hibernate.cfg.Configuration.parseMappingElement(Configuration.java:1621)
    at org.hibernate.cfg.Configuration.parseSessionFactory(Configuration.java:1589)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1568)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:1542)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1462)
    at org.hibernate.cfg.Configuration.configure(Configuration.java:1448)
    at hibDomain.HibernateUtil.buildSessionFactory(HibernateUtil.java:11)
    ... 29 more
Caused by: org.hibernate.MappingException: class com.hib.User not found while looking for property: firstName
    at org.hibernate.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:97)
    at org.hibernate.mapping.SimpleValue.setTypeUsingReflection(SimpleValue.java:302)
    at org.hibernate.cfg.HbmBinder.createProperty(HbmBinder.java:2193)
    at org.hibernate.cfg.HbmBinder.createClassProperties(HbmBinder.java:2170)
    at org.hibernate.cfg.HbmBinder.createClassProperties(HbmBinder.java:2060)
    at org.hibernate.cfg.HbmBinder.bindRootPersistentClassCommonValues(HbmBinder.java:381)
    at org.hibernate.cfg.HbmBinder.bindRootClass(HbmBinder.java:295)
    at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:166)
    at org.hibernate.cfg.Configuration.add(Configuration.java:702)
    at org.hibernate.cfg.Configuration.addInputStream(Configuration.java:537)
    at org.hibernate.cfg.Configuration.addResource(Configuration.java:599)
    ... 36 more
Caused by: java.lang.ClassNotFoundException: com.hib.User
    at java.lang.ClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:352)
    at org.mortbay.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:337)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at org.hibernate.util.ReflectHelper.classForName(ReflectHelper.java:123)
    at org.hibernate.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:93)
    ... 46 more
[ERROR] 500 - POST /rpctest/testService (127.0.0.1) 57 bytes
   Request headers
      Accept: */*
      X-GWT-Permutation: HostedMode
      X-GWT-Module-Base: http://127.0.0.1:8888/rpctest/
      Content-Type: text/x-gwt-rpc; charset=utf-8
      Referer: http://127.0.0.1:8888/Rpctest.html?gwt.codesvr=127.0.0.1:9997
      Accept-Language: en-us
      Accept-Encoding: gzip, deflate
      User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
      Host: 127.0.0.1:8888
      Content-Length: 168
      Connection: Keep-Alive
      Cache-Control: no-cache
   Response headers
      Content-Type: text/plain

入口点类

package rpctest.client;

import rpctest.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Rpctest implements EntryPoint {

    final TextBox firstName = new TextBox();
    final TextBox lastName = new TextBox();
    final Button ans = new Button("Add User");
    final Label label1 = new Label("First Name");
    final Label label2 = new Label("Last Name");
    //final Label errorLabel = new Label();
    private VerticalPanel mainpanel = new VerticalPanel();
    private HorizontalPanel addpanel1 = new HorizontalPanel();
    private HorizontalPanel addpanel2 = new HorizontalPanel();
    private final RpctestServiceAsync calNumbers = GWT
            .create(RpctestService.class);

    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {

        addpanel1.add(label1);
        addpanel1.add(firstName);
        addpanel2.add(label2);
        addpanel2.add(lastName);
        mainpanel.add(addpanel1);
        mainpanel.add(addpanel2);
        mainpanel.add(ans);

        ans.addClickHandler(new ClickHandler() {

            @Override
            public void onClick(ClickEvent event) {

            String name1 = firstName.getValue();    
            String name2 = lastName.getValue();

            calNumbers.addUser(name1,name2,
                new AsyncCallback<String>() {
                public void onFailure(Throwable caught) {
                    // Show the RPC error message to the user
                        Window.alert("check your inputs");
                    }

                @Override
                public void onSuccess(String result) {
                // TODO Auto-generated method stub
                    Window.alert("User is ->"+result);
                }
            });}
        });
        // We can add style names to widgets
        //sendButton.addStyleName("sendButton");

        // Add the nameField and sendButton to the RootPanel
        // Use RootPanel.get() to get the entire body element

        /*RootPanel.get("nameFieldContainer").add(nameField);
         * 
        RootPanel.get("sendButtonContainer").add(sendButton);
        RootPanel.get("errorLabelContainer").add(errorLabel);*/
        RootPanel.get().add(mainpanel);

    }
}

接口

package rpctest.client;

import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;

@RemoteServiceRelativePath("testService")
public interface RpctestService extends RemoteService {

    String addUser(String firstName,String lastName) throws IllegalArgumentException;
}


package rpctest.client;

import com.google.gwt.user.client.rpc.AsyncCallback;

public interface RpctestServiceAsync {

    void addUser(String firstName, String lastName,
            AsyncCallback<String> callback);

}

实施

package rpctest.server;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import hibDomain.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.Transaction;
import hibDomain.User;
import hibDomain.Task;

import rpctest.client.RpctestService;

public class RpctestServiceImpl extends RemoteServiceServlet  implements RpctestService {

        public String addUser(String name1, String name2)
            throws IllegalArgumentException {

              Transaction trns = null;
              Session session = HibernateUtil.getSessionFactory().openSession();
              try {
               trns = session.beginTransaction();

               User user = new User();

               user.setFirstName(name1);
               user.setLastName(name2);

               session.save(user);

               session.getTransaction().commit();
              } catch (RuntimeException e) {
               if(trns != null){
                trns.rollback();
               }
               e.printStackTrace();
              } finally{
               session.flush();
               session.close();
              }

            return name1; 
    }

}

Hibernate文件

package hibDomain;

public class User {
 private Integer id;
 private String firstName;
 private String lastName;

 public Integer getId() {
  return id;
 }
 public void setId(Integer id) {
  this.id = id;
 }
 public String getFirstName() {
  return firstName;
 }
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 public String getLastName() {
  return lastName;
 }
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
}

映射文件

<?xml version="1.0"?>
<!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.hib.User" table="users" >
  <id name="id" type="int" column="id" >
   <generator class="native"/>
  </id>

  <property name="firstName">
   <column name="first_name" />
  </property>
  <property name="lastName">
   <column name="last_name"/>
  </property>
 </class>
</hibernate-mapping>

cfg文件

<?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/userdata</property>
  <property name="connection.username">root</property>
  <property name="connection.password"></property>

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

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

  <!-- Enable Hibernate's automatic session context management -->
  <property name="current_session_context_class">thread</property>

  <!-- Disable the second-level cache -->
  <property name="cache.provider_class">org.hibernate.cache.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>

  <!-- Mapping files -->
  <mapping resource="user.hbm.xml"/>
  <mapping resource="task.hbm.xml"/>

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

的Util

package hibDomain;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
 private static final SessionFactory sessionFactory = buildSessionFactory();
 private static SessionFactory buildSessionFactory() {
  try {
   // Create the SessionFactory from hibernate.cfg.xml
   return new Configuration().configure().buildSessionFactory();
  }
  catch (Throwable ex) {
   // Make sure you log the exception, as it might be swallowed
   System.err.println("Initial SessionFactory creation failed." + ex);
   throw new ExceptionInInitializerError(ex);
  }
 }
 public static SessionFactory getSessionFactory() {
  return sessionFactory;
 }
}

1 个答案:

答案 0 :(得分:0)

您的hibernate类文件(User)位于“hibDomain”包中。你正在制作的地图是“com.hib.User”。将此更改为hibDomain.User,可能工作。