0

尝试使用使用 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。

不知道我做错了什么。

4

4 回答 4

5

IfFROM子句包含多个实体,而您只需要其中一个,请在以下位置指定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(); 

否则,您将获得实体元组为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(); 
于 2011-03-12T21:27:08.663 回答
1

The best way to do so is:

Query query = session.createQuery(queryString).addEntity(<Class Name>.class);
<Class Name> obj = (<Class Name>)query.uniqueResult();

Finally it worked for me try it...

于 2012-06-07T04:15:19.483 回答
0

尝试

session.beginTransaction();
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();
于 2011-03-12T21:28:05.183 回答
0

.addEntity(User.class)您可以通过在查询末尾添加来解决此问题。例如 :

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().addEntity(User.class);
于 2012-10-16T12:31:53.973 回答