【问题标题】:can any body explain what this exception mean?任何机构都可以解释这个例外是什么意思吗?
【发布时间】:2013-07-18 21:01:58
【问题描述】:

我正在尝试基于 jersey + JPA + Glasfish 3.1 + java 6u43 + Gson lib 构建一个用于 json 处理的 Web 服务 但我遇到了一个非常令人沮丧的异常。

java.lang.ClassCastException: com.hm.model.User 无法转换为 com.hm.model.User

我没有将 user 转换为 user ,但异常让我不知何故 user 对象正在转换回 user 。请帮助我理解这一点。

来自 glasfish server.log 的详细异常快照

com.sun.jersey.api.core.WebAppResourceConfig|_ThreadID=24;_ThreadName=Thread-1 Scanning for root resource and provider classes in the Web app resource paths:
 /WEB-INF/lib
 /WEB-INF/classes|#]

com.sun.jersey.api.core.ScanningResourceConfig|_ThreadID=24;_ThreadName=Thread-1;|Root resource classes found:
class com.hm.dam.Users|#]

com.sun.jersey.api.core.ScanningResourceConfig|_ThreadID=24;_ThreadName=Thread-1;|No provider classes found.|#]

com.sun.jersey.server.impl.application.WebApplicationImpl|_ThreadID=24;_ThreadName=Thread-1;|Initiating Jersey application, version 'Jersey: 1.5 01/14/2011 12:36 PM'|#]

javax.enterprise.system.container.web.com.sun.enterprise.web|_ThreadID=42;_ThreadName=Thread-1;|WEB0671: Loading application [HMWService] at [/HMWService]|#]

javax.enterprise.system.tools.admin.org.glassfish.deployment.admin|_ThreadID=42;_ThreadName=Thread-1;|HMWService was successfully deployed in 1,100 milliseconds.|#]

javax.enterprise.system.std.com.sun.enterprise.server.logging|_ThreadID=161;_ThreadName=Thread-1;|[EL Fine]: 2013-07-19 01:05:35.01--ServerSession(233673454)--Connection(2052351957)--Thread(Thread[http-thread-pool-8080(4),5,grizzly-kernel])--SELECT user_id, DOB, EMAIL, EXPERIENCE, first_name, inser_user_id, insert_dt, join_dt, last_name, nic_passport, PASSWORD, STATUS, update_dt, update_user_id, USERNAME, gender_ref_id FROM users

com.sun.jersey.spi.container.ContainerResponse|_ThreadID=32;_ThreadName=Thread-1;|The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.ClassCastException: com.hm.model.User cannot be cast to com.hm.model.User
at com.hm.dam.Users.read(Users.java:57)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)`

这就是我的项目结构的样子。 我从包含名为“用户”的表的数据库中构建了一个带有 pojo 类的 JPA 项目 这是我的 pojo 和 persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="HMbeans" transaction-type="RESOURCE_LOCAL">
    <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>

    <class>com.hm.model.User</class>
    <exclude-unlisted-classes>false</exclude-unlisted-classes>
    <properties>
        <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/hotel_management"/>
        <property name="javax.persistence.jdbc.user" value="root"/>
        <property name="javax.persistence.jdbc.password" value="123456"/>
        <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
        <property name="eclipselink.logging.level" value="FINER"/>
        <property name="eclipselink.logging.exceptions" value="true"/>
        <property name="eclipselink.logging.session" value="true"/>
        <property name="eclipselink.logging.connection" value="true"/>
    </properties>
</persistence-unit>
</persistence>

现在用户实体 pojo。

@Entity
@Table(name="users")
public class User implements Serializable {
private static final long serialVersionUID = 1L;

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

@Column(name="first_name")
private String firstName;

@Column(name="last_name")
private String lastName;

private String password;

public User() {
}

public String getUserId() {
    return this.userId;
}

public void setUserId(String userId) {
    this.userId = userId;
}

public String getFirstName() {
    return this.firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return this.lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}   

public String getPassword() {
    return this.password;
}

public void setPassword(String password) {
    this.password = password;
}
}

现在这是我在 HMWService 动态 web 项目中的 web 服务类

package com.hm.dam;
...

@Path("/users")
public class Users 
{
EntityManager em = JPAUtil.getEntityManager() ;

    @POST
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/readUser")
    public String read(@FormParam("userId") String User_Id) {


       // User u = em.find(User.class, User_Id);
        User u=null;
       Iterator<User> it =  em.createQuery("SELECT u FROM User u").getResultList().iterator();
       if(it.hasNext())
       {
           u=it.next();
           System.out.println(u.getFirstName());
       }
       if(u!=null)
       return new Gson().toJson(u);
       else
           return new Gson().toJson("");

    }      
}

最后这是我的 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>HMWService</display-name>

<servlet>
    <servlet-name>Jersey Web Application</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>Jersey Web Application</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>
<!--  <persistence-context-ref>
    <persistence-context-ref-name>persistence/em</persistence-context-ref-name>
    <persistence-unit-name>HMentites</persistence-unit-name>
</persistence-context-ref> -->
</web-app>

我编写了一个 index.jsp 来测试 Web 服务。它包含一个带有 post 方法的表单。在提交浏览器上显示上述异常

<h1>JAX-RS @FormQuery Testing</h1>

<form action="rest/users/readUser" method="post">
    <p>
        Id : <input type="text" name="userId" />
    </p>

    <input type="submit" value="Read User" />
</form>

例外 java.lang.ClassCastException: com.hm.model.User 无法转换为 com.hm.model.User

【问题讨论】:

    标签: jakarta-ee jpa glassfish


    【解决方案1】:

    热部署到您的 glassfish 服务器(如果您使用该服务器)可能存在问题。尝试清理和构建您的项目,看看是否有帮助。

    如果没有帮助,这个问题通常发生在一个类被两个不同的Classloaders 加载时。

    有许多不同的解决方案,请查看this questionthis question

    【讨论】:

    • 谢谢 unwichtich .. 你的回复给了我方向。是的,我正在使用 eclipse 在运行服务器上进行部署。我清理并重建代码然后异常消失了。但我不明白刚刚通过清洁发生了什么。以及两个类加载器如何使用同一个类。虽然我将我的 JPA 实体项目作为 jar 文件放在 WEB 动态项目中。你能解释一下吗?我还对persistence.xml 进行了一些更改,并使其使用JTA 数据源。并尝试使用内置的 EJB 容器在 web 服务“用户”类中获取持久性实体管理器。最终它解决了问题:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 1970-01-01
    相关资源
    最近更新 更多