Weird java.lang.ClassCastException thrown

I am experimenting with JPA and Glassfish 4.0.

I wrote such a user class (only the relevant parts, and I'm not sure if it compiles):

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

My TestController (only relevant parts):

@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 "";

}

And my country bean is just a simple bean with simple attributes located in:

dk.iqtools.entity

In general, it works, but if I encounter an error in my code, I persistently get the following error:

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)

allegation of violation:

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

Can someone tell me why this is happening? If everything works as expected, the user will be inserted into the database. But if for instanse I try to insert a user that already exists, I get a database error.

. , .

GF, .

.

.

+4
2

- - EntityManagerFactory , , .

, EntityManagerFactory , ServletContextListeners , -.

ServletContextListener: http://4dev.tech/2015/08/example-of-servletcontextlistener-implementation/

+1

; " X X". "X" - .

, . pom.xml (maven makefile), , "" (, ) WAR . EAR.

jar ( ). , , .

, WAR pom.xml, , EAR file pom jar .

, , "clean", WAR EAR, .

, WAR EAR, WAR, .

0

All Articles