我正在试验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 countryList = cq.getResultList();
User user = new User();
user.setFirstName("Hans123");
user.setLastName("Knudsen333");
user.setCountry((Country)countryList.get(0));
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实例才能摆脱它.
不是很像生产.
感谢您的任何意见.