抛出奇怪的java.lang.ClassCastException

时间:2013-11-08 21:55:18

标签: java jpa glassfish classcastexception

我正在尝试使用JPA和Glassfish 4.0。

我写过这样的用户类(只是相关部分,我不确定它是否编译):

public class User implements Serializable {
   private static final long serialVersionUID = 1L;
   @Id
   @GeneratedValue(strategy = GenerationType.IDENTITY)
   @Basic(optional = false)
   @Column(name = "id")
   private Integer id;
   @Basic(optional = false)
   @NotNull
   @Size(min = 1, max = 50)
   @Column(name = "first_name")
   private String firstName;

   @JoinColumn(name = "country_id", referencedColumnName = "id")
   @ManyToOne(optional = false)
   private Country country;

   public void setCountry(Country countryId) {
      this.country = countryId;
   }
}

我的TestController(只是相关部分):

@ManagedBean(name = "testController", eager = true)
@RequestScoped
public class TestController implements Serializable {
   @EJB
   private dk.iqtools.session.UserFacade userFacade; 

   public String Insert(){
      factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
      EntityManager em = factory.createEntityManager();
      Query cq = em.createQuery("select c from Country c where c.id = 302");
      List<Country> countryList = cq.getResultList();

  User user = new User();
  user.setFirstName("Hans123");
  user.setLastName("Knudsen333");
  user.setCountry((Country)countryList.get(0));  <- throws an ERROR
  user.setPassword("secret");
  user.setYearOfBirth(1966);
  user.setGender(1);
  user.setEmail("haps@hfhfh.dk2243");

  userFacade.create(user);

 return "";

}

我的Country bean只是一个简单的bean,位于:

dk.iqtools.entity

一般情况下它可以工作,但是如果我在代码中遇到错误,我会一直收到以下错误:

Caused by: java.lang.ClassCastException: 
dk.iqtools.entity.Country cannot be cast to dk.iqtools.entity.Country
at dk.iqtools.controller.TestController.Insert(TestController.java:65)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)

令人不快的陈述是:

user.setCountry((Country)countryList.get(0));

有人可以告诉我为什么会这样吗?如果一切按预期运行,则将用户插入数据库。但是,如果我为instanse尝试插入已存在的用户,则会收到数据库错误。

下次通过我收到奇怪的例外。我无法理解为什么一个班级不能投入自己。

我必须重新启动我的GF实例才能摆脱它。

不像生产一样。

感谢您的任何意见。

2 个答案:

答案 0 :(得分:2)

这是因为来自旧版应用程序的EntityManagerFactory的一些遗留问题,不知何故,在重新部署应用程序后,它的类加载器仍然存在。

您需要做的是在重新部署之前关闭EntityManagerFactory,您可以使用ServletContextListeners来实现这一点,它们允许您将事件附加到您的Web应用程序初始化和销毁​​。

以下是ServletContextListener实现的一个非常简单的示例:http://4dev.tech/2015/08/example-of-servletcontextlistener-implementation/

答案 1 :(得分:1)

我只需要处理这种类型的异常; “不能将X投射到X.” “X”是同一类。

事实证明,两个问题相互影响。我在我的一些代码的pom.xml文件(maven的makefile)中做了一个更改,该文件说我的类是“要包含”(编译而不是提供)在WAR文件中。但它也可以在“外部”EAR模块中使用。

类加载器处理同一个jar文件的2个不同实例(即2个副本)。这使得类加载器认为它是2个不同的类,导致异常。

要最终修复它,我必须将编译更改为在WAR文件pom.xml中提供,但请确保EAR文件的pom确实包含项目jar文件。

但是我还必须采取措施确保我已经运行“干净”以删除所有WAR和EAR文件的jar库内容,以便找不到额外的副本。

由于WAR在EAR中而且你必须取消压缩WAR以获取其内容的列表并多次为不同的日期运行构建,因此解析文件的内容会让人感到困惑。文件。