GWT Hibernate 程序中的错误 2

发布于 2024-12-17 18:48:54 字数 16306 浏览 0 评论 0原文

我设法从帖子 stackoverflow post 关于 GWT 的提示中解决了这个问题。这篇文章告诉我们,由于 JDBC 应该位于客户端,而不是服务器端。

我正在尝试制作一个简单的 Web 应用程序,使用 GWT RPC 与 Hibernate、MySql 和 Hibernate 将用户添加到数据库; Eclipse IDE。我已经有一个简单版本的休眠程序正在运行&现在我尝试使用 GWT RPC 做同样的事情。

尽管在将 hibernate 与 RPC 结合使用时可能存在某些不同的做法。首先,我必须将 jars/libs 添加到 war/web.inf/lib add 中,然后再将它们添加到类路径中,同时我在 src 中创建了一个简单的文件夹,将所有 jars/libraries 放入该文件夹中。然后添加到简单的休眠应用程序的类路径中。继续,编译器随后引发有关 cfg.xml 和 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;
 }
}

映射文件 strong>

<?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;
 }
}

I manage to solve this problem getting hint from post stackoverflow post about GWT. The post tells that as JDBC shouldn'e be on client side, rather on server side.

I am trying to make a simple web application that adds a user to database using GWT RPC with Hibernate, MySql & eclipse IDE. I have already a simple version of hibernate program running & now I am trying to do same using GWT RPC.

Though probably there are certain different practices when using hibernate with RPC. Firstly I had to put jars/libs to war/web.inf/lib add before adding them to classpath, while I made a simple folder in src, put all jars/libraries to that & then added to classpath for simple hibernate app. It continues, compiler then raised error about unavailability of cfg.xml & mapping files which were in the hibernate files package(that contain pojo files). I moved them to src folder & error gone. But now error is about session creation. This time moving Util file to src did not work.

This is directory structure of my project:

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

I am using MySQL on Windows 7.
Here are the error messages & my code.

errors

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

entry point class

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

    }
}

interfaces

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

}

Implementation

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 files

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

mapping file

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

<?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;
 }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

紫南 2024-12-24 18:48:54

您的休眠类文件(用户)位于“hibDomain”包中。您正在制作的映射是针对“com.hib.User”的。将其更改为 hibDomain.User,它可能可以工作。

Your hibernate class file (User) is in "hibDomain" package. where as the mapping you are making is for "com.hib.User". change this to hibDomain.User and it might work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文