Hibernate createQuery() 抛出 ClassCastException,Transformer 没有帮助
尝试使用使用 Hibernate 3.6 和 MySQL5.1 来选择实体,但我不断收到 ClassCastException。
@Entity
@Table( name = "USER" )
public class User {
@Id
@Column(name= "user_id")
private Long userId;
@OneToOne()
@JoinColumn(name="status_id")
protected UserStatusType userStatusType;
@OneToOne()
@JoinColumn(name="region_id")
protected Region region;
@Entity
@Table( name = "REGION" )
public class Region
@Id
@Column(name = "region_id")
private Long regionId
@Entity
@Table( name = "USER_STATUS_TYPE" )
public class UserStatusType
@Id
@Column(name = "type_id")
private Long typeId
当尝试在 createQuery() 中使用 HQL 时,我不断收到 ClassCastException:
session.beginTransaction();
User user = (User)session.createQuery(
"from User u, UserStatusType ust, Region r "
+ " where u.userId = ? and u.userStatusType.typeId = ust.typeId"
+ " and u.region.regionId = r.regionId")
.setLong(0, 42L)
.uniqueResult();
java.lang.ClassCastException:
[Ljava.lang.Object; cannot be cast to com.scd.dao.entity.User
我尝试使用 setResultTransformer(Transformers.aliasToBean(User.class)),但这给了我一个 NullPointerException。
不确定我做错了什么。
Trying to SELECT an entity using Using Hibernate 3.6 and MySQL5.1 but I keep getting a ClassCastException.
@Entity
@Table( name = "USER" )
public class User {
@Id
@Column(name= "user_id")
private Long userId;
@OneToOne()
@JoinColumn(name="status_id")
protected UserStatusType userStatusType;
@OneToOne()
@JoinColumn(name="region_id")
protected Region region;
@Entity
@Table( name = "REGION" )
public class Region
@Id
@Column(name = "region_id")
private Long regionId
@Entity
@Table( name = "USER_STATUS_TYPE" )
public class UserStatusType
@Id
@Column(name = "type_id")
private Long typeId
When attempting to use HQL in createQuery() I keep getting a ClassCastException:
session.beginTransaction();
User user = (User)session.createQuery(
"from User u, UserStatusType ust, Region r "
+ " where u.userId = ? and u.userStatusType.typeId = ust.typeId"
+ " and u.region.regionId = r.regionId")
.setLong(0, 42L)
.uniqueResult();
java.lang.ClassCastException:
[Ljava.lang.Object; cannot be cast to com.scd.dao.entity.User
I tried using setResultTransformer(Transformers.aliasToBean(User.class)), but that gave me a NullPointerException.
Not sure what I'm doing wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
尝试
try
您可以通过在查询末尾添加
.addEntity(User.class)
来解决此问题。例如 :You can solve this issue by adding
.addEntity(User.class)
in the end of the query. For example :如果
FROM
子句包含多个实体,而您只需要其中一个,请在SELECT
中指定它:否则您将获得实体元组作为
Object[]
。如果您确实需要急切获取而不是内部联接,请使用
JOIN FETCH
:If
FROM
clause contains several entities, and you need only one of them, specify it inSELECT
:Otherwise you'll get the tuple of entities as
Object[]
.If you actually need eager fetching instead of inner join, use
JOIN FETCH
:最好的方法是:
最后它对我有用,尝试一下......
The best way to do so is:
Finally it worked for me try it...