use*_*584 0 hibernate classcastexception
尝试使用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
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
我尝试使用setResultTransformer(Transformers.aliasToBean(User.class)),但这给了我一个NullPointerException.
不知道我做错了什么.
如果FROM子句包含多个实体,并且您只需要其中一个实体,请在SELECT以下位置指定:
User user = (User)session.createQuery(
"select u "
+ "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();
Run Code Online (Sandbox Code Playgroud)
否则你将获得实体的元组Object[].
如果您确实需要提取而不是内连接,请使用JOIN FETCH:
User user = (User)session.createQuery(
"from User u "
+ "join fetch u.userStatusType join fetch u.region "
+ " where u.userId = ?")
.setLong(0, 42L)
.uniqueResult();
Run Code Online (Sandbox Code Playgroud)