ClassCastException试图将检索到的JPA对象强制转换为具体类

时间:2009-12-20 03:26:11

标签: hibernate scala jpa classcastexception

我不确定我做错了什么,但是我有一个类中有一个类,所以当我保存Skill类时,用户类也会被创建,所以当我做连接时我想拉一切都在,我得到一个classcastexception。

这就是我调用查询的方式。

val retrieved_obj = em.createNamedQuery("findAllSkillsByUser").setParameter("username", user.username ).getResultList().asInstanceOf[java.util.List[Skill]]
assertEquals(1, retrieved_obj.size())
val retrieved = retrieved_obj.get(0).asInstanceOf[Skill]

这是我的查询: <query><![CDATA[from Skill a JOIN a.user u WHERE u.username=:username]]></query>

这就是hibernate在我的测试中实际做的事情:

Hibernate: insert into users (firstName, lastName, username, id) values (?, ?, ?, ?)
Hibernate: insert into skills (datestarted, name, position, rating, skill_user_fk, id) values (?, ?, ?, ?, ?, ?)
Hibernate: select skill0_.id as id64_0_, user1_.id as id63_1_, skill0_.datestarted as datestar2_64_0_, skill0_.name as name64_0_, skill0_.position as position64_0_, skill0_.rating as rating64_0_, skill0_.skill_user_fk as skill6_64_0_, user1_.firstName as firstName63_1_, user1_.lastName as lastName63_1_, user1_.username as username63_1_ from skills skill0_ inner join users user1_ on skill0_.skill_user_fk=user1_.id where user1_.username=?

我希望问题是select中的所有user1部分。

Skill类基本上只有一些setter / getter,所以我删除了大部分注释但是外键一个:

  var id : Int = _
  var name : String = ""
  var position : Int = _
  var dateStarted : Date = new Date()
  var rating : SkillRating.Value = SkillRating.unknown

  @OneToOne{val fetch = FetchType.EAGER, val cascade=Array(CascadeType.PERSIST, CascadeType.REMOVE)}
  @JoinColumn{val name = "skill_user_fk", val nullable = false}
  var user : User = _

这是User类:

  var id : Int = _
  var firstName : String = ""
  var lastName : String = ""
  var username : String = ""

这是我的错误:

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to jblack.resumeapp.lift.model.Skill

我宁愿不只是选择技能属性,然后必须为用户做另一个查询,因为随着我的类变得更复杂,效率会降低。

1 个答案:

答案 0 :(得分:2)

您选择 SkillUser并返回包含两个元素的对象数组。

你可以这样对待它或稍微改写你的查询:

select a from Skill a JOIN FETCH a.user u WHERE u.username=:username

仅选择Skill,但会获取并填充其User关联。